Skip to content

Instantly share code, notes, and snippets.

@vonNiklasson
Created November 29, 2017 12:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vonNiklasson/8abe1a9c194da50f8e9ecc058b4f1a6d to your computer and use it in GitHub Desktop.
Save vonNiklasson/8abe1a9c194da50f8e9ecc058b4f1a6d to your computer and use it in GitHub Desktop.
Merge Javascript objects recursively
function merge(obj1, obj2) {
var isAnyType = function(obj) { return (typeof obj !== "undefined" ); }
var isSingleType = function(obj) { return (typeof obj === "string" || typeof obj === "number"); }
var isObjectType = function(obj) { return (typeof obj === "object" && !isArrayType(obj)); }
var isArrayType = function(obj) { return Array.isArray(obj); }
if (isAnyType(obj1) && !isAnyType(obj2)) {
return obj1;
}
else if (isAnyType(obj2) && !isAnyType(obj1)) {
return obj2;
}
else if (isSingleType(obj1) && isSingleType(obj2)) {
return obj1;
}
else if (isSingleType(obj1) && !isSingleType(obj2)) {
return obj2;
}
else if (isSingleType(obj2) && !isSingleType(obj1)) {
return obj1;
}
else if ((isObjectType(obj1) && isArrayType(obj2)) ||
(isObjectType(obj2) && isArrayType(obj1))) {
throw "Illegal Array and Object merge";
}
else if (isArrayType(obj1) && isArrayType(obj2)) {
return obj1.concat(obj2);
}
else if (isObjectType(obj1) && isObjectType(obj2)) {
retObj = {};
for (var attr in obj1) {
retObj[attr] = merge(obj1[attr], obj2[attr]);
}
for (var attr in obj2) {
if (obj1.hasOwnProperty(attr)) continue;
retObj[attr] = merge(obj2[attr], obj1[attr]);
}
return retObj;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment