Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

merge JSON objects without new keys

How to merge two JSON objects but do not include properties that don't exist in the first Object?

Input

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 appears to only block the immediate extension of properties and not deeper ones.

like image 498
vsync Avatar asked Oct 09 '22 14:10

vsync


1 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 } }
like image 146
vsync Avatar answered Oct 13 '22 11:10

vsync