我需要合并价格相同的对象并添加数量 ( amount
)。
例子:
[
{price: 25.1, amount: 32},
{price: 45.2, amount: 45},
{price: 25.1, amount: 25},
{price: 44.0, amount: 13},
{price: 45.2, amount: 23}
]
结果:
[
{price: 25.1, amount: 57}, // 32 + 25
{price: 45.2, amount: 68}, // 45 + 23
{price: 44.0, amount: 13},
]
您可以使用Array#reduce
对象来存储每个价格的金额。
const example = [
{price: 25.1, amount: 32},
{price: 45.2, amount: 45},
{price: 25.1, amount: 25},
{price: 44.0, amount: 13},
{price: 45.2, amount: 23}
]
const res = Object.values(example.reduce((acc,{price,amount})=>
((acc[price] = acc[price] || {price, amount: 0}).amount += amount, acc), {}));
console.log(res);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句