【问题标题】:Sum the value of a property from obejcts that are matching in another property, from an array of objects对对象数组中与另一个属性匹配的对象的属性值求和
【发布时间】:2022-09-23 16:22:40
【问题描述】:

我有一个对象数组,我试图根据它们的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 来合并数组中的对象吗?

谢谢!

    标签: javascript


    【解决方案1】:

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

    【讨论】:

    • 如果我想将原始数组中对象的其他属性包含到最终结果中怎么办?
    • 您可以更新逻辑来执行此操作,具体取决于您希望如何将其他属性包含到最终结果中。我将更新答案以了解这可能如何工作。不能保留每个值,因为输出数组长度小于输入。
    猜你喜欢
    • 2022-11-21
    • 2020-04-09
    • 2018-03-11
    • 1970-01-01
    • 2022-11-10
    • 2013-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多