Merge JSON objects without new keys

How to combine two JSON objects, but not include properties that do not exist in the first object?

Enter

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. There is a method for objects called preventExtensions , but it seems to block the immediate extension of properties, not the deeper ones.

+5
source share
2 answers
/*
    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 } }
+4
source

A minor tweak to the solution, adding support for arrays (replacing rather than adding will be harder):

function merge(obj1, obj2) {
    for( var p in obj2 )
        if( obj1.hasOwnProperty(p) )
            obj1[p] = (typeof obj2[p] === 'object' && !(p.length)) ? merge(obj1[p], obj2[p]) : obj2[p];

    return obj1;
}
0
source

All Articles