合并没有新密钥的JSON对象

合并没有新密钥的JSON对象

问题描述:

如何合并两个JSON对象但不包含第一个对象中不存在的属性?

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:'' };



输出



Output

obj1 = { x:1, y:{ a:1, b:2 } };



ps。对象的方法称为 preventExtensions 但它似乎只是阻止属性的立即扩展而不是更深层次的扩展。


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 } }