我有一个包含多个对象的数组,如下所示
[{Name: "Product A", Qty: "5"}, {Name: "Product B", Qty: "2"}, {Name: "Product A", Qty: "6"}]
,并且想知道如何合并相关产品NAME中的对象QTY字段值以产生如下所示的新数组:
[{Name: "Product A", Qty: "11"}, {Name: "Product B", Qty: "2"}]
任何对此的帮助将不胜感激。谢谢
答案 0 :(得分:2)
您可以使用reduce
创建一个对象并使用Object.values
获取值。
const data = [{Name: "Product A", Qty: "5"}, {Name: "Product B", Qty: "2"}, {Name: "Product A", Qty: "6"}]
const result = data.reduce((r, {Name, Qty}) => {
if(!r[Name]) r[Name] = {Name, Qty: +Qty};
else r[Name].Qty += +Qty;
return r;
}, {})
console.log(Object.values(result))