Merge objects like obj1 and obj2 to get obj3 in javascript.
obj1 = [{fruit: \'watermelon\', sweetness: 3},{fruit: \'banana\', sweetness: 4},{fruit: \'apple\', sw
You can first create a hashtable
by merging similar objects using #forEach and then extract the required array using a #map() function - see demo below:
var obj1 = [{fruit: 'watermelon', sweetness: 3},{fruit: 'banana', sweetness: 4},{fruit: 'apple', sweetness: 5}],
obj2 = [{fruit_name: 'apple', color: 'red'},{fruit_name: 'banana', color:'yellow'},{fruit_name: 'watermelon', color:'green'}], hash = {};
// function to create a hashtable
function classify(e) {
if(hash[e.fruit] || hash[e.fruit_name]) {
Object.keys(e).forEach(function(c){
hash[e.fruit || e.fruit_name][c] = e[c];
});
} else {
hash[e.fruit_name || e.fruit] = e;
}
}
// add to hash
obj1.forEach(classify);
obj2.forEach(classify);
// extract the result
var obj3 = Object.keys(hash).map(function(e){
delete hash[e]['fruit'];
return hash[e];
});
console.log(obj3);
.as-console-wrapper{top:0;max-height:100%!important;}