【问题标题】:Merge objects by the same value in an array [duplicate]按数组中的相同值合并对象[重复]
【发布时间】:2020-12-04 16:05:29
【问题描述】:

我需要合并价格相同的对象并添加数量(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},
]

【问题讨论】:

    标签: javascript arrays


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-24
      • 2020-02-08
      • 2017-11-12
      • 2018-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多