我有一个像这样的数组:
const arr = [
{ price: 12, desc: 'desc', id: 123, qty: 1 },
{ price: 12, desc: 'desc', id: 123, qty: 1 },
{ price: 12, desc: 'desc', id: 123, qty: 1 }
];
我希望能够删除x
项的数量,直到只剩下一个ID为123
的项目。但是我也希望通过具有相同ID的许多其他项目来增加该项目的数量。
所以我想要一个像这样的结果数组:
const result = [ { price: 12, desc: 'desc', id: 123, qty: 3 } ];
答案 0 :(得分:1)
您可以使用函数reduce
对匹配的ID进行分组和计数。
const arr = [{ price: 12, desc: 'desc', id: 123, qty: 1 },{ price: 12, desc: 'desc', id: 123, qty: 1 },{ price: 12, desc: 'desc', id: 123, qty: 1 }];
// The function Object.values returns the values of every object, for example:
// accumulator = {
// "123": { price: 12, desc: 'desc', id: 123, qty: 3 }
// }
// The function Object.values returns:
// { price: 12, desc: 'desc', id: 123, qty: 3 }
const result = Object.values(arr.reduce((a, c) => {
// The accumulator 'a' will contain objects as follow:
// {'123': {id: 123, desc: 'desc'...., qty: 2}}
// This line checks for the current object with 'c.id'
// If that object doesn't exist, a new object is created with
// a further property called 'qty' and then we add +1
(a[c.id] || (a[c.id] = Object.assign(c, {qty: 0}))).qty++;
return a;
}, {}));
console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }