-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
    Welcome to Stack Overflow! StackOverflow is not a free coding service. You're expected to [try to solve the problem first](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users). Please update your question to show what you have already tried in a [mcve]. For further information, please see [ask], and take the [tour] :) – Barmar Oct 14 '19 at 09:44
  • See https://stackoverflow.com/questions/40603913/search-recursively-for-value-in-object-by-property-name to get started. – Barmar Oct 14 '19 at 09:45
  • Do you want to get number of objects with this id `123`? – brk Oct 14 '19 at 09:46
  • thanks, but my data have about xx.000 item, which solution best – Huynh Nhọn Oct 14 '19 at 09:48
  • @brk yes, count quality object have id =123 – Huynh Nhọn Oct 14 '19 at 09:49
  • 1
    The simplest version would be two loops. So what have you tried so far? – Andreas Oct 14 '19 at 09:50

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
  • 46,805
  • 5
  • 49
  • 71