javascript - 通过属性javascript计算数组对象侧面数组中的对象
问题描述
我有如下数据:
var data = [
{
items: [
{
id: 123
},
{
id: 234
},
{
id: 123
}
]
}, {
items: [
{
id: 123
},
{
id: 234
}
]
}
]
所以,我想通过属性'id'在所有数据中的数组深处计算对象。例如:data.countObject('id',123) //return 3.
我的数据有大约 xx.000 项,哪种解决方案最好?感谢您的帮助(对不起我的英语)
解决方案
您可以使用reduce
& forEach
。在reduce
回调内部,您可以使用where &只是回调函数的参数来访问items
数组。然后你可以用来获取数组中的每个对象curr.items
acc
curr
curr.items.forEach
items
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))
推荐阅读
- sql - 如果 from 和 to date 为空,如何获取最近 7 天的数据?
- c# - 实时图表地理地图
- javascript - Sharepoint 2010 - jQuery CEWP 仅在编辑模式下加载
- ios - 如何在 iOS swift 中从 scn 文件中为子节点设置动画?
- docker - 在无 Internet 区域中独立设置 Docker swarm
- linux - Raspberry Pi 3 B+ 的 GIT 克隆失败
- c# - 如何更改 double.ToString() 的标准格式;
- docker - 如何在 Docker Swarm / Kubernetes 中根据 Web 请求启动 Docker 容器的新实例?
- html - HTML5 视频在移动浏览器中不起作用
- react-native - 我想在谷歌地图中使用纬度和经度在反应原生中绘制多边形