Merging objects within an array and keeping the highest value for identical properties

痞子三分冷 提交于 2020-01-04 05:31:06

问题


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

What I want is to keep the highest value available for the same property.

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.

I want to end up with this object: {"1":1,"2":2,"3":1,"5":1}.


回答1:


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

Note: I've updated your test case to have higher values before lower values, to better demonstrate the solution.

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);



回答2:


With vanilla javascript:

function getData(obj) {
    var d = {};
    for (var index in obj) {
        var item = obj[index];
        for (var k in item) {
            if (!d[k]) d[k] = item[k];
            else d[k] = Math.max(d[k], item[k]);
        }
    }
    console.log(d);
    return d;
}
getData([null, null, { "1": 1 }, { "2": 1 }, { "3": 1 }, { "2": 2 }, { "5": 1 }]);



回答3:


You can do it with _.mergeWith from Lodash library.

var input = [null, null, {"1":1},{"2":1},{"3":1},{"2":2},{"5":1}];
var output = _.mergeWith({}, ...input, (obj, src) => obj > src ? obj : src);



回答4:


Libraries increase vendor size, So don't prefer it for such small purpose.

let input = [null, null, {"1":1},{"2":1},{"3":1},{"2":2},{"5":1}];
let output = {};

for(i in input) {
   let item = input[i];
   for(j in item)
     output[j] = item[j];
}

console.log(output);


来源:https://stackoverflow.com/questions/44982659/merging-objects-within-an-array-and-keeping-the-highest-value-for-identical-prop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!