合并数组中的对象并保持相同属性的最大值 [英] Merging objects within an array and keeping the highest value for identical properties

查看:100
本文介绍了合并数组中的对象并保持相同属性的最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个数组,我想合并其中的对象。

I have this array and I would like to merge the objects within it.

[null, null, {"1":1},{"2":1},{"3":1},{"2":2},{"5":1}]

我考虑过使用类似这样的东西:

I thought about using something like this:

var o1 = { a: 1, b: 1, c: 1 };
var o2 = { b: 2, c: 2 };
var o3 = { c: 3 };

var obj = Object.assign({}, o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }

但是,该属性被具有相同属性的其他对象覆盖(稍后按参数顺序

However, the properties are overwritten by other objects that have the same properties later in the parameters order

我要保留的是可用于同一物业的最高价值

在我的示例中,我有 { 2:1} { 2:2} ,我想保留 { 2:2} ,因为 2 2 属性的最高可用值。

In my example, I have {"2":1} and {"2":2}, I would like to keep the {"2":2} because 2 is the highest value available for the "2" property.

我想结束此对象: { 1:1, 2:2, 3:1, 5:1}

推荐答案

使用 Array#reduce 将数组转换为对象,并使用 Array#forEach 迭代数组中每个对象的键。

Use Array#reduce to convert the array to an object, and iterate the keys of each object in the array using Array#forEach.

注意:我已经将您的测试用例更新为具有较高的值,然后再使用较低的值,以更好地演示解决方案。

const arr = [null, null, {"1":0},{"2":3},{"5": 25},{"3":1},{"2":2},{"5":1},{"1":-5}];

const result = arr.reduce((r, o) => {
  if(!typeof(o) === 'object' || o === null) {
    return r;
  }
  
  Object.keys(o) // iterate the keys
    .forEach((key) => r[key] = r[key] !== undefined ? Math.max(r[key], o[key]) : o[key]); // get the greatest value
  
  return r;
}, {});

console.log(result);

这篇关于合并数组中的对象并保持相同属性的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆