Merge objects like obj1 and obj2 to get obj3 in javascript.
obj1 = [{fruit: \'watermelon\', sweetness: 3},{fruit: \'banana\', sweetness: 4},{fruit: \'apple\', sw
let obj1 = [{fruit: 'watermelon', sweetness: 3},{fruit: 'banana', sweetness: 4},{fruit: 'apple', sweetness: 5}];
let obj2 = [{fruit_name: 'apple', color: 'red'},{fruit_name: 'banana', color:'yellow'},{fruit_name: 'watermelon', color:'green'}];
function regulate(a) {
return a.map(v => {
if (v.fruit) {
v.fruit_name = v.fruit;
delete v.fruit;
}
return v;
});
}
let a = [].concat(regulate(obj1), regulate(obj2));
let merged = [];
a.reduce((m, v) => {
let f = m.filter(v2 => v2.fruit_name === v.fruit_name);
if (f.length > 0) {
Object.assign(f[0], v);
} else {
m.push(v);
}
return m;
}, merged);
console.log(merged);