我有以下这样的数组
[
{name: "calpol", quantity: 12},
{name: "paracetamol", quantity: 15},
{name: "paracetamol", quantity: 10},
]
当产品相同时,我想总结数量,这样我就可以获得像这样的数组:
[
{name: "calpol", quantity: 12},
{name: "paracetamol", quantity: 25},
]
答案 0 :(得分:2)
使用reduce并在累加器数组中检查是否存在名称如calpol或扑热息痛的对象。如果存在,则更新数量,否则创建新对象并将其推入累加器
let prod = [{
name: "calpol",
quantity: 12
},
{
name: "paracetamol",
quantity: 15
},
{
name: "paracetamol",
quantity: 10
},
]
let sum = prod.reduce(function(acc, curr) {
let findIndex = acc.findIndex(item => item.name === curr.name);
if (findIndex === -1) {
acc.push(curr)
} else {
acc[findIndex].quantity += curr.quantity
}
return acc;
}, [])
console.log(sum)