首页 > 解决方案 > 通过属性javascript计算数组对象侧面数组中的对象

问题描述

我有如下数据:

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

所以,我想通过属性'id'在所有数据中的数组深处计算对象。例如:data.countObject('id',123) //return 3. 我的数据有大约 xx.000 项,哪种解决方案最好?感谢您的帮助(对不起我的英语)

标签: javascriptarraysjsonobjectcount

解决方案


您可以使用reduce& forEach。在reduce回调内部,您可以使用where &只是回调函数的参数来访问items数组。然后你可以用来获取数组中的每个对象curr.itemsacccurrcurr.items.forEachitems

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))


推荐阅读