简体   繁体   English

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

[英]Merging items of array of object if they have equal keys

Array of objects that I got我得到的对象数组

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

Array of objects that I am trying to do我正在尝试做的对象数组

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

I am merging and getting the average price for duplicated objects .我正在合并并获取重复对象平均价格

What I have done:我做了什么:

I have tried to use filter() function but I removed the duplicated without merging the prices.我曾尝试使用filter()函数,但我在没有合并价格的情况下删除了重复项。

You can use .reduce() with an ES6 Map .您可以将.reduce()与 ES6 Map 一起使用 By using reduce() you can accumulate all objects into a Map, where the key is the id from the object and the value is an accumulated array of price values for the given id .通过使用reduce()您可以将所有对象累积到一个 Map 中,其中键是对象的id ,值是给定idprice值的累积数组。 You can then convert the Map back into an array using Array.from() , where you can provide a mapping function to convert the [key, value] pairs from the map into an object.然后,您可以使用Array.from()Map转换回数组,您可以在其中提供映射函数将[key, value]对从映射转换为对象。 The object's price key will be the sum of all numbers in the value array ( arr ) divided by the length of the array, which will give you the average.对象的price键将是value数组 ( arr ) 中所有数字的总和除以数组的长度,这将为您提供平均值。

See example below:请参阅下面的示例:

 const arr = [ { "id": 1, "price": 100 }, { "id": 1, "price": 80 }, { "id": 2, "price": 8 }, { "id": 1, "price": 85 } ]; const res = Array.from(arr.reduce((m, {id, price}) => { return m.set(id, [...(m.get(id) || []), price]); }, new Map), ([id, arr]) => ({id, price: arr.reduce((t, n) => t+n, 0) / arr.length})); console.log(res);

If you want to avoid extra loops and extra properties is not a problem, you can use a getter for each object as follow:如果你想避免额外的循环并且额外的属性不是问题,你可以为每个对象使用一个 getter,如下所示:

You can use the function Array.prototype.reduce for grouping objects by id and the function Object.values for extracting the grouped values.您可以使用函数Array.prototype.reduceid对对象进行分组,使用函数Object.values来提取分组值。

The getter price calculates the average when this property is accessed. getter price计算访问此属性时的平均值。

Extra properties:额外属性:

{
    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; }

Use forEach loop and build an object with keys as id and aggregate price.使用forEach循环并使用键作为id和聚合价格构建一个对象。 Use Object.values of above object and calculate the averages.使用上述对象的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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM