我有一个数组:
[
{
"id": "#1",
"quantity": 2
},
{
"id": "#2",
"quantity": 1
},
{
"id": "#3",
"quantity": 1
},
{
"id": "#1",
"quantity": 2
},
{
"id": "#2",
"quantity": 1
},
{
"id": "#3",
"quantity": 1
}
]
我希望结果看起来像
[
{
"id": "#1",
"quantity": 4
},
{
"id": "#2",
"quantity": 2
},
{
"id": "#3",
"quantity": 2
}
]
基本上将具有相同ID的对象组合在一起,并将数量相加。 我可以使用2 for循环来做到这一点。但是有没有更优化的方法来解决这个问题?
答案 0 :(得分:1)
一个选项是首先将数组缩减为对象,如果键相同则添加数量,然后获取对象的值:
var arr = [
{
"id": "#1",
"quantity": 2
},
{
"id": "#2",
"quantity": 1
},
{
"id": "#3",
"quantity": 1
},
{
"id": "#1",
"quantity": 2
},
{
"id": "#2",
"quantity": 1
},
{
"id": "#3",
"quantity": 1
}
]
console.log(
Object.values(arr.reduce((obj, rec) => {
if(obj[rec.id] === undefined) {
obj[rec.id] = rec;
} else {
obj[rec.id].quantity += rec.quantity;
}
return obj;
}, {}))
)

答案 1 :(得分:1)
这样的事情可以胜任:
function transform(a) {
const seen = {};
const ret = [];
a.forEach(o => {
const id = o.id;
seen[id] = (seen[id] || 0) + o.quantity;
});
for (let key in seen) {
ret.push({
id: key,
quantity: seen[key]
});
}
return ret;
}
console.log(transform([{
"id": "#1",
"quantity": 2
}, {
"id": "#2",
"quantity": 1
}, {
"id": "#3",
"quantity": 1
}, {
"id": "#1",
"quantity": 2
}, {
"id": "#2",
"quantity": 1
}, {
"id": "#3",
"quantity": 1
}]));