javascript - 从对象数组中删除重复项并在 JavaScript 中添加新值(例如数量)
问题描述
我有一个包含对象数组的对象。我想删除重复的对象,我想给它附加新的值,比如数量。
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());
推荐阅读
- node.js - Web 套接字在连接建立之前关闭
- php - 如何在 postmeta 值中获取带有“按 ASC 排序”日期的 meta_value 的结果?
- arcgis-js-api - 如何允许用户在 Javascript for ArcGIS 中使用两个过滤器
- neural-network - 我应该在训练数据中包含没有对象的图像吗
- python-3.x - 即使用户拥有所有权限,AWS机械土耳其人请求错误
- regex - 64个字符长的十六进制字符串的正则表达式
- nginx - 为什么 Nginx 服务器忽略“client_max_body_size 100M;” 指示?
- reactjs - React Components - 避免重新渲染
- python - 如何为很难找到的特定 div 抓取 html 网站?
- typescript - 从对象中删除属性但保留类型