在JavaScript中从对象数组中删除重复项并添加新值(例如Quantity)



我有一个对象,它包含一个对象数组。我想删除重复的对象,我想用新值(如quantity)附加它。

const data = [{
id: "B01",
image: "https://i.ibb.co/zmdvMfD/zinger-stacke-burger.png",
title: "Zinger Stack",
price: 3.99,
},
{
id: "B01",
image: "https://i.ibb.co/zmdvMfD/zinger-stacke-burger.png",
title: "Zinger Stack",
price: 3.99,
},
{
id: "F01",
image: "https://i.ibb.co/zmdvMfD/zinger-stacke-burger.png",
title: "Zinger Stack",
price: 3.99,
},
{
id: "F01",
image: "https://i.ibb.co/zmdvMfD/zinger-stacke-burger.png",
title: "Zinger Stack",
price: 3.99,
},
]

这就是我想要达到的目标

const data = [
{
id: "B01",
image: "https://i.ibb.co/zmdvMfD/zinger-stacke-burger.png",
title: "Zinger Stack",
price: 3.99,
quantity: 2
},
{
id: "F01",
image: "https://i.ibb.co/zmdvMfD/zinger-stacke-burger.png",
title: "Zinger Stack",
price: 3.99,
quantity: 2
}
]

这是我的解决方案。有什么更快捷的方法来达到同样的结果吗?

let ids = data.map((o) => o.id);
let uniqueList = data.filter(({ id }, index) => !ids.includes(id, index + 1));
console.log("uniqueList", uniqueList);

const result = uniqueList.map((item) => {
return {
...item,
quantity: (data.reduce((totalType, item) => {
if (!totalType[item.id]) {
totalType[item.id] = 0;
}

totalType[item.id]++;

return totalType;
}, {}))[item.id]
};
});
console.log("result >", result);

您可以通过一个简单的迭代实现这一点:

const map = new Map();
data.forEach((item) => {
if (map.has(item.id)) {
map.get(item.id).quantity++;
}
else {
map.set(item.id, {
...item,
quantity: 1
})
}
});
const result = Array.from(map.values());

最新更新