最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Get count of true values in JSON with javascript - Stack Overflow

programmeradmin0浏览0评论

I have a JSON object like this:

filters: {
        module: {
            value: "All",
            active: false
        },
        dates: {
            value: [],
            active: true
        }
    }

How to count active filters, based on this object?

I have a JSON object like this:

filters: {
        module: {
            value: "All",
            active: false
        },
        dates: {
            value: [],
            active: true
        }
    }

How to count active filters, based on this object?

Share Improve this question asked Aug 19, 2018 at 7:05 MartyMarty 5548 silver badges30 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 3

Use reduce to iterate over the values of each object, extract the active property from each, and add that boolean to the accumulator, which will coerce it to a number:

const obj = {
  filters: {
    module: {
      value: "All",
      active: false
    },
    dates: {
      value: [],
      active: true
    },
    foo: {
      value: "All",
      active: false
    },
    bar: {
      value: [],
      active: true
    }
  }
};

console.log(
  Object.values(obj.filters).reduce((a, { active }) => a + active, 0)
);

Get all the keys inside the filters using Object.keys which will give an array and then use reduce function to count the number of active true

let someObj = {
  filters: {
    module: {
      value: "All",
      active: false
    },
    dates: {
      value: [],
      active: true
    }
  }

};

let count = Object.keys(someObj.filters).reduce(function(acc, curr) {
  if (someObj.filters[curr].active === true) {
    acc += 1;
  }
  return acc;
}, 0);

console.log(count)

You can use Object.keys() and filter()

var filters = {
        module: {
            value: "All",
            active: false
        },
        dates: {
            value: [],
            active: true
        }
    }
    
var active = Object.keys(filters).filter(k => filters[k].active);

console.log(active.length)

You can try this

var filters = {
  module: {
    value: "All",
    active: false
  },
  dates: {
    value: [],
    active: true
  }
};

console.log(Object.values(filters).filter(element => element.active === true).length)

Hope this helps !

发布评论

评论列表(0)

  1. 暂无评论