如何从具有相同ID的数组中删除多个项目,但在增加其“qty”时保留一个项目?

时间:2018-04-11 14:22:41

标签: javascript arrays object

我有一个像这样的数组:

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 } ];

1 个答案:

答案 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; }