Skip to content

Instantly share code, notes, and snippets.

@sinemetu1
Created February 3, 2012 21:49
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sinemetu1/1732896 to your computer and use it in GitHub Desktop.
Save sinemetu1/1732896 to your computer and use it in GitHub Desktop.
javaScript function that merges two JSON objects with the second object taking precedence in the event of a collision.
function mergeDeep (o1, o2) {
var tempNewObj = o1;
//if o1 is an object - {}
if (o1.length === undefined && typeof o1 !== "number") {
$.each(o2, function(key, value) {
if (o1[key] === undefined) {
tempNewObj[key] = value;
} else {
tempNewObj[key] = mergeDeep(o1[key], o2[key]);
}
});
}
//else if o1 is an array - []
else if (o1.length > 0 && typeof o1 !== "string") {
$.each(o2, function(index) {
if (JSON.stringify(o1).indexOf(JSON.stringify(o2[index])) === -1) {
tempNewObj.push(o2[index]);
}
});
}
//handling other types like string or number
else {
//taking value from the second object o2
//could be modified to keep o1 value with tempNewObj = o1;
tempNewObj = o2;
}
return tempNewObj;
};
@pociej
Copy link

pociej commented Jul 31, 2014

what about boolean ?

o1.length === undefined && typeof o1 !== "number" is true for boolean variables

@sspmrsomebody1
Copy link

sspmrsomebody1 commented Apr 27, 2018

Works like a charm! Thanks!
Also I edited it to only use vanilla JavaScript (FINALLY FIGURED OUT HOW TO USE CODE BLOCK FORMATTING PROPERLY):

function mergeDeep (o1, o2) {
    var tempNewObj = o1;

    //if o1 is an object - {}
    if (o1.length === undefined && typeof o1 !== "number") {
        for(key in o2) {
            value=o2[key]
            if (o1[key] === undefined) {
                tempNewObj[key] = value;
            } else {
                tempNewObj[key] = mergeDeep(o1[key], o2[key]);
            }
        }
    }

    //else if o1 is an array - []    I THINK I BROKE IT ._.
    else if (o1.length > 0 && typeof o1 !== "string") {
        for(index in o2) {
            if (JSON.stringify(o1).indexOf(JSON.stringify(o2[index])) === -1) {
                tempNewObj.push(o2[index]);
            }
        }
    }

    //handling other types like string or number
    else {
        //taking value from the second object o2
        //could be modified to keep o1 value with tempNewObj = o1;
        tempNewObj = o2;
    }
    return tempNewObj;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment