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

I have a JSON object like this:filters: {module: {value: "All",active: false},dates: {value:

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 !

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745261625a4619235.html

相关推荐

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

    I have a JSON object like this:filters: {module: {value: "All",active: false},dates: {value:

    3小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信