How to merge two object values by keys
You want a deep extend
$.extend(true, {}, x, y);
See the docs for jQuery.extend([deep], target, object1[, objectN])
The simple javascript function without depending jQuery will help you to merge two JSON object which has nested objects.
function mergeJSON(source1,source2){
/*
* Properties from the Souce1 object will be copied to Source2 Object.
* Note: This method will return a new merged object, Source1 and Source2 original values will not be replaced.
* */
var mergedJSON = Object.create(source2);// Copying Source2 to a new Object
for (var attrname in source1) {
if(mergedJSON.hasOwnProperty(attrname)) {
if ( source1[attrname]!=null && source1[attrname].constructor==Object ) {
/*
* Recursive call if the property is an object,
* Iterate the object and set all properties of the inner object.
*/
mergedJSON[attrname] = mergeJSON(source1[attrname], mergedJSON[attrname]);
}
} else {//else copy the property from source1
mergedJSON[attrname] = source1[attrname];
}
}
return mergedJSON;
}
The new spread operator from the ES2018 provides some nice way to do this:
function combine(...list){
return list.reduce(
(a,b)=>{
return {...a,...b}
}
)
}
// work as expected with simple objects
console.log(
combine(
{x:3,z:1},
{x:4,m:4},
{a:1},
{b:2}
));
// is not a good recursive solution
console.log(
combine(
{x:3,z:1,child:{c:1}},
{x:4,m:4,child:{d:3}},
{a:1},
{b:2}
));
This was the best recursive solution that I could get
function combine_recursive(...list) {
return list.reduce(
(a,b) => {
// for non objects return b if exists or a
if ( ! ( a instanceof Object ) || ! ( b instanceof Object ) ) {
return b !== undefined ? b : a;
}
// for objects, get the keys and combine them
const keys = Object.keys(a).concat(Object.keys(b));
return keys.map(
key => {
return {[key]: combine_recursive(a[key],b[key])}
}
).reduce(
(x,y) => {
return {...x,...y}
}
);
}
)
}
// testing recursive and the priority
console.log(
combine_recursive(
{x:3,z:1,child:{c:1,k:1}},
{x:4,m:4,child:{d:3,k:2}},
{a:1},
{b:2}
));
// using the example of the question
var x ={ "student-marks":{'math':1,'physics':5} };
var y ={ "student-marks":{'chemistry':3,'history':2} };
console.log( combine_recursive(x,y) );