翻過(guò)高山走不出你
2023-11-12 22:17:36
如何連接兩個(gè)數(shù)組,更新“qty”鍵而不重復(fù)“title”鍵?例子:對(duì)象1obj1 = [{ id: 0, qty: 1, title: "HEINEKEN0 350ML"}]對(duì)象2obj2 = [ { id: 0, qty: 5, title: "HEINEKEN0 350ML" }, { id: 1, qty: 1, title: "HEINEKEN0 600ML" }];我需要的輸出:output = [ { id: 0, qty: 6, title: "HEINEKEN0 350ML" }, { id: 1, qty: 1, title: "HEINEKEN0 600ML" } ];
1 回答

開(kāi)滿天機(jī)
TA貢獻(xiàn)1786條經(jīng)驗(yàn) 獲得超13個(gè)贊
您可以將兩個(gè)數(shù)組連接在一起并Array#reduce與一個(gè)對(duì)象一起使用來(lái)存儲(chǔ)每個(gè)標(biāo)題的值。
const obj1 = [{
id: 0,
qty: 1,
title: "HEINEKEN0 350ML"
}],
obj2 = [{
id: 0,
qty: 5,
title: "HEINEKEN0 350ML"
},
{
id: 1,
qty: 1,
title: "HEINEKEN0 600ML"
}];
const res = Object.values([...obj1, ...obj2].reduce((acc,{title,qty,id})=>{
(acc[title] = acc[title] || {id,qty: 0,title}).qty += qty;
return acc;
}, {}));
console.log(res);
添加回答
舉報(bào)
0/150
提交
取消