5

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.

3
  • 2
    Phrase the question in the question, post the answer as an answer, and accept it. Commented Nov 3, 2011 at 15:18
  • 3
    @vsync: It's a great idea to post solutions to help other people in the future, but you should format it as follows; 1) Post a question "pretending" to ask the question, 2) post your solution as an answer to your own question, and accept your own answer as the solution. Who knows, you might even get another answer giving a different (better?) approach! Commented Nov 3, 2011 at 15:18
  • good idea, I will do as you advised Commented Nov 3, 2011 at 15:33

2 Answers 2

4
/*
    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 } }
Sign up to request clarification or add additional context in comments.

5 Comments

please REFACTOR this to the max
You should use continue instead of break to skip a property; currently it stops the complete loop if it encounters a non-existing property.
I have refactored my code since, to use 'prop IN obj' testing
I'm wondering why you don't use obj1.hasOwnProperty(p) as well. It's only about properties that obj1 has itself without the prototype ones.
=> I wonder if I could just settle with if( p in obj1 ) instead of the hasOwnProperty
0

Minor tweak to the solution, adding support for arrays (replace, not append - that would 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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.