输入
var obj1 = { x:'',y:{ a:'',b:'' } };
var obj2 = { x:1,y:{ a:1,b:2,c:3 },z:'' };
产量
obj1 = { x:1,b:2 } };
PS.有一个名为preventExtensions的对象的方法,但它似乎只阻止属性的立即扩展而不是更深的属性.
最佳答案
/*
Recursively merge properties of two objects
ONLY for properties that exist in obj1
*/
var obj1 = { x:'',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,b:2 } }