How to merge two JSON objects but do not include properties that don't exist in the first Object?
var obj1 = { x:'', y:{ a:'', b:'' } };
var obj2 = { x:1, y:{ a:1, b:2, c:3 }, z:'' };
obj1 = { x:1, y:{ a:1, b:2 } };
ps. There is a method for Objects called preventExtensions but it appears to only block the immediate extension of properties and not deeper ones.
/*
Recursively merge properties of two objects
ONLY for properties that exist in obj1
*/
var obj1 = { x:'', y:{ a:'', b:'' } };
var obj2 = { x:1, y:{ a:1, b:2, c:3 }, z:'' };
function merge(obj1, obj2) {
for( var p in obj2 )
if( obj1.hasOwnProperty(p) )
obj1[p] = typeof obj2[p] === 'object' ? merge(obj1[p], obj2[p]) : obj2[p];
return obj1;
}
merge(obj1, obj2 );
console.dir( obj1 ); // { x:1, y:{ a:1, b:2 } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With