I want to merge two arrays of objects. The keys are the same but the values might not always be the same.
Any solution is appreciated preferably in javascript, but
You could use a Map for keeping same id
in the same object and Object.assign for creating independent objects.
var g = [{ id: 36, name: 'AAA', goal: 'yes', 'random': 27 }, { id: 40, name: 'BBB', goal: 'yes' }, { id: 39, name: 'JJJ', goal: 'yes' }, { id: 27, name: 'CCC', goal: 'yes', lag: "23.3343" }],
c = [{ id: 36, name: 'AAA', goal: 'yes', color: "purple" }, { id: 40, name: 'BBB', circle: 'yes', color: "purple" }, { id: 100, name: 'JJJ', circle: 'yes' }],
map = new Map,
result = g.concat(c).reduce(function (r, o) {
var temp;
if (map.has(o.id)) {
Object.assign(map.get(o.id), o);
} else {
temp = Object.assign({}, o);
map.set(temp.id, temp);
r.push(temp);
}
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Version without reduce and without concat.
function merge(o) {
var temp;
if (map.has(o.id)) {
Object.assign(map.get(o.id), o);
return;
}
temp = Object.assign({}, o);
map.set(temp.id, temp);
result.push(temp);
}
var g = [{ id: 36, name: 'AAA', goal: 'yes', 'random': 27 }, { id: 40, name: 'BBB', goal: 'yes' }, { id: 39, name: 'JJJ', goal: 'yes' }, { id: 27, name: 'CCC', goal: 'yes', lag: "23.3343" }],
c = [{ id: 36, name: 'AAA', goal: 'yes', color: "purple" }, { id: 40, name: 'BBB', circle: 'yes', color: "purple" }, { id: 100, name: 'JJJ', circle: 'yes' }],
map = new Map,
result = [];
[g, c].forEach(function (a) {
a.forEach(merge);
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Here's a Python solution. This modifies g
, which you may or may not want.
c_by_id = {d['id']: d for d in c}
for item in g:
item.update(c_by_id.get(item['id']), {})
This can be easily achieved by underscore functions _.uniq
and _.union
.
Just use this:
var finalData = _.uniq(_.union(c, g), function (ele) {
return ele.id
})
This will return you what you are looking for.