问题
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