【发布时间】:2020-06-03 13:00:06
【问题描述】:
情况就是这样:每个订单可以包含多种类型,数量不同。对于每个订单项目,我想要每种类型的总数量。
[{
"order" : 1,
"orderDetails" : [{
"quantity" : 10,
"product" : {
"productType" : "A"
},
"quantity" : 20,
"product" : {
"productType" : "A"
},
"quantity" : 10,
"product" : {
"productType" : "B"
}
}]
}]
这是我的代码,它可以完成这项工作,但我正试图让它变得更加优雅,不知何故。我很确定那里有冗余代码,我不确定我是否正确使用了 reduce
const orders = data.map(h => {
const newArray = [];
h.orderDetails_ = h.orderDetails.reduce(function(a, b, i) {
if (newArray[b.product.productType] == undefined) {
newArray[b.product.productType] = b.quantity;
return newArray;
} else {
newArray[b.product.productType] += b.quantity;
return newArray;
}
}, 0);
return h;
});
【问题讨论】:
标签: arrays dictionary ecmascript-6 reduce