简体   繁体   中英

how to count keys present in array of object in javascript?

I have an below array. I wanted to know how many time selectedOption key is present in array of Object. In, some object we don't have key selectedOption . So, the count of key selectedOption should return 4. How we can count these key in javascript?

let data = [{
  id: 123,
  selectedOption: "ABC",
  value: 345
}, {
  id: 234,
  selectedOption: "BCD",
  value: 345
}, {
  id: 356,
  selectedOption: "BGY",
  value: 678
}, {
  id: 456,
  selectedOption: "BCD",
  value: 890
}, {
  id: 870: value: 980
}, {
  id: 385,
  value: 654
}]
data.filter(datum => datum.selectedOption).length

data.filter(d => d.hasOwnProperty('selectedOption')).length

This is a more full proof solution compared to data.filter(datum => datum.selectedOption).length because if selectedOption was a boolean flag with false value it wouldn't be counted.

hasOwnProperty will check if the property exists on the object irrespective of the value.

For example in this case

let data = [{
  id: 123,
  selectedOption: false,
  value: 345
}, {
  id: 234,
  selectedOption: false,
  value: 345
}, {
  id: 356,
  selectedOption: true,
  value: 678
}, {
  id: 456,
  selectedOption: false,
  value: 890
}, {
  id: 870,
  value: 980
}, {
  id: 385,
  value: 654
}];
  1. data.filter(d => d.hasOwnProperty('selectedOption')).length Output: 4

  2. data.filter(datum => datum.selectedOption).length Output: 1

There are multiple ways it can be done. In the below function,reduce is used. Inside reduce callback it is checking if the object has selectedOption key then increment 1

 let data = [{ id: 123, selectedOption: "ABC", value: 345 }, { id: 234, selectedOption: "BCD", value: 345 }, { id: 356, selectedOption: "BGY", value: 678 }, { id: 456, selectedOption: "BCD", value: 890 }, { id: 870, value: 980 }, { id: 385, value: 654 }]; let countSelectedOption = data.reduce((acc, curr) => { acc += curr.selectedOption? 1: 0; return acc; }, 0); console.log(countSelectedOption)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM