我有一个对象数组:
var array = [{
id: "cards",
amount: 5
}, {
id: "shirts",
amount: 3
}, {
id: "cards",
amount: 2
}, {
id: "shirts",
amount: 3
}]
我需要做的是遍历此数组并查找所有id类型的总数。因此,在此示例中,我将找到卡片和衬衫的总数。
我不确定如何对对象执行此操作。我尝试使用剥离对象Object.values(array)
,但是有没有办法用这些对象呢?
谢谢你的帮助。
这应该做您想要的:
var array = [
{ id: "cards", amount: 5 },
{ id: "shirts", amount: 3 },
{ id: "cards", amount: 2 },
{ id: "shirts", amount: 3 }
];
var result = array.reduce(function(entities, item) {
entities[item.id] = (entities[item.id] || 0) + item.amount;
return entities;
}, {})
console.log(result);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句