-3

I have data like:

var data = [
  {
    items: [
      {
        id: 123
      },
      {
        id: 234
      },
      {
        id: 123
      }
    ]
  }, {
    items: [
      {
        id: 123
      },
      {
        id: 234
      }
    ]
  }
]

so, I want count object deep in array inside of all data by property 'id'. ex: data.countObject('id',123) //return 3. and my data have about xx.000 item, which solution best? Thanks for help (sorry for my English)

1 Answers1

1

You can use reduce & forEach. Inside the reduce callback you can access the items array using curr.items where acc & curr are just parameters of the call back function. Then you can use curr.items.forEach to get each object inside items array

var data = [{
  items: [{
      id: 123
    },
    {
      id: 234
    },
    {
      id: 123
    }
  ]
}, {
  items: [{
      id: 123
    },
    {
      id: 234
    }
  ]
}];

function getCount(id) {

  return data.reduce(function(acc, curr) {
    // iterate through item array and check if the id is same as
    // required id. If same then add 1 to the accumulator
    curr.items.forEach(function(item) {
      item.id === id ? acc += 1 : acc += 0;
    })
    return acc;
  }, 0) // 0 is the accumulator, initial value is 0
}

console.log(getCount(123))
brk
  • 48,835
  • 10
  • 56
  • 78