Merge objects like obj1 and obj2 to get obj3 in javascript.
obj1 = [{fruit: \'watermelon\', sweetness: 3},{fruit: \'banana\', sweetness: 4},{fruit: \'apple\', sw
It's fairly simple to put together a generic function to merge two arrays of objects with a shared key. The easiest way to do it is to use a mapping based on an associate array, as follows. Note that you could use this routine to solve any problem of a similar type, but it definitely works with your data--see the JSFiddle linked at the end.
(ETA: The shared key is added only once, with the name provided as key1; if you want the second key to wind up in the output, simply swap the pairs of arguments to the function.)
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'}];
function mergeObjectArrays(array1, key1, array2, key2) {
var map = []; // an associative array/hashtable
var arrayValue, mapValue, propertyNames, propertyName, propertyValue;
// 1. Loop over one array, populating the map by each object's specified key
for(var x = 0; x < array1.length; x++) {
array1Value = array1[x];
map[array1Value[key1]] = array1Value;
map.push(array1Value);
}
// 2. Loop over the other array, matching on the provided keys
for(var x = 0; x < array2.length; x++) {
arrayValue = array2[x];
mapValue = map[arrayValue[key2]];
if (typeof(mapValue) != 'undefined') { // add all missing non-keyed properties to the mapped/merged object
propertyNames = Object.keys(arrayValue);
for (var y = 0; y < propertyNames.length; y++) {
propertyName = propertyNames[y];
if (propertyName != key1 && propertyName != key2) { // .. as that shared value is already added
propertyValue = arrayValue[propertyName];
mapValue[propertyName] = propertyValue;
}
}
}
else { // it's missing from the mapping, so at least add it though it will be missing array1 data
map[arrayValue[key2]] = arrayValue;
map.push(arrayValue);
}
}
return map;
}
var mergedArrays = mergeObjectArrays(obj1, 'fruit', obj2, 'fruit_name');
Here's a working sample.