Created
November 29, 2017 12:11
-
-
Save vonNiklasson/8abe1a9c194da50f8e9ecc058b4f1a6d to your computer and use it in GitHub Desktop.
Merge Javascript objects recursively
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 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