Created
February 3, 2012 21:49
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}; |
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
what about boolean ?
o1.length === undefined && typeof o1 !== "number" is true for boolean variables