如果键具有相等的键,则合并对象数组的项

时间:2020-09-06 14:37:07

标签: javascript arrays

我得到的对象数组

  [
    {
      "id": 1,
      "price": 100
    },
    {
      "id": 1,
      "price": 80
    },
    {
      "id": 2,
      "price": 8
    },
    {
      "id": 1,
      "price": 85
    }
  ]

我要尝试的对象数组

  [
    {
      "id": 1,
      "price": 88.33 // AVERAGE VALUE BETWEEN DUPLICATED OBJECTS
    },
    {
      "id": 2,
      "price": 8
    }
  ]

我正在合并并获取 重复对象的平均价格

我做了什么:

我尝试使用filter()函数,但是我删除了重复项而不合并价格。

3 个答案:

答案 0 :(得分:1)

您可以将.reduce()与ES6 Map一起使用。通过使用reduce(),您可以将所有对象累积到Map中,其中键是对象中的id,并且值是给定{{1} }。然后,您可以使用Array.from()price转换回数组,在其中您可以提供映射功能,以将id对从映射转换为对象。对象的Map键将是[key, value]数组(price)中所有数字的总和除以数组的长度,这将为您提供平均值。

请参见以下示例:

value

答案 1 :(得分:1)

如果要避免多余的循环和多余的属性不是问题,可以为每个对象使用吸气剂,如下所示:

您可以使用函数Array.prototype.reduce通过id对对象进行分组,并使用函数Object.values来提取分组的值。

访问该属性时,getter price计算平均值。

其他属性:

{
    count: Integer // count of repeated ids.
    sum: Double // total sum of prices
}

const arr = [    {      "id": 1,      "price": 100    },    {      "id": 1,      "price": 80    },    {      "id": 2,      "price": 8    },    {      "id": 1,      "price": 85    }  ],
      result = Object.values(arr.reduce((r, {id, price}) => {
        let current = (r[id] || (r[id] = {id, sum: 0, count: 0, get price() {
          return this.sum / this.count;
        }}));

        current.sum += price;
        current.count++;

        return r;
      }, {}));

console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:0)

使用forEach循环并使用键为id和总价来构建对象。 使用上述对象的Object.values并计算平均值。

const data = [
  {
    id: 1,
    price: 100,
  },
  {
    id: 1,
    price: 80,
  },
  {
    id: 2,
    price: 8,
  },
  {
    id: 1,
    price: 85,
  },
];

const process = (arr) => {
  const res = {};
  arr.forEach(({ id, price }) => {
    res[id] ??= { id, sum: 0, count: 0 };
    res[id].sum += price;
    res[id].count += 1;
  });
  return Object.values(res).map(({ id, sum, count }) => ({
    id,
    price: sum / count,
  }));
};

console.log(process(data));