如何对reduce创建的数组的属性值求和



这是我的代码

var array = 
[
{
id: "BG",
qty: 100
}, 
{
id: "BG",
qty: 35
}, 
{
id: "JP",
qty: 75
},
{
id: "JP",
qty: 50
}
];

var result = array.reduce((obj, cur) => (obj[cur.id] = [...(obj[cur.id] || []), cur], obj), {})
console.log(result);

我想做的是根据array.reduce所做的ID将数组分组为子数组。但现在我想把数量加起来。

所以我希望BG的总数量=35,JP的总数量为125,然后我希望能够对这些数字运行数学条件

以前确实有人问过它,但当我搜索它时,我也可以写了。没有那么长。

var array = [{
id: "BG",
qty: 100
},
{
id: "BG",
qty: 35
},
{
id: "JP",
qty: 75
},
{
id: "JP",
qty: 50
}
];
var result = Object.values(array.reduce(function(agg, item) {
agg[item.id] = agg[item.id] || {
id: item.id,
qty: 0
}
agg[item.id].qty += item.qty;
return agg;
}, {}));
console.log(result);

最新更新