繁体   English   中英

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

[英]How to remove multiple items from an array with the same id, but keep one while increasing its “qty”?

我有一个这样的数组:

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

您可以使用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; } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM