求和对象数组中另一个属性中匹配的obejct中一个属性的值



我有一个对象数组,我试图根据数组中每个对象的address属性求和amount属性的值

我想转换这样的东西:

[
{
amount: 10,
address: a01,
...other props...
},
{
amount: 20,
address: b02,
...other props...
},
{
amount: 5,
address: a01,
...other props...
},
...
]

至:

[
{
address: a01,
totalAmount: 15,
...other props...
},
{
address: b02,
totalAmount: someTotaledAmount,
...other props...
},
...
]

我应该使用reduce来合并阵列中的对象吗?

谢谢!

您肯定可以使用Array.reduce()来按地址求和。我们会创建一个对象,为每个地址值创建一个条目。

然后我们可以使用Object.values()来获得作为数组的结果。

let input = [ { amount: 10, address: 'a01', otherValue: 'x' }, { amount: 20, address: 'b02', otherValue: 'y' }, { amount: 5, address: 'a01', otherValue: 'z' } ]
const result = Object.values(input.reduce((acc, { amount, address, ...rest }) => { 
acc[address] = acc[address] || { address, ...rest, totalAmount: 0 };
acc[address].totalAmount += amount;
return acc;
} , {}));
console.log('Result:', result);
.as-console-wrapper { max-height: 100% !important; }

您也可以使用for ... of循环来做同样的事情:

let input = [ { amount: 10, address: 'a01', otherValue: 'x' }, { amount: 20, address: 'b02', otherValue: 'y' }, { amount: 5, address: 'a01', otherValue: 'z' } ]
let result = {};
for(let { amount, address, ...rest} of input) {
if (!result[address]) {
result[address] = { address, ...rest, totalAmount: 0 };
}
result[address].totalAmount += amount;
}
result = Object.values(result);
console.log('Result:', result);
.as-console-wrapper { max-height: 100% !important; }

最新更新