Last active
July 30, 2016 09:03
-
-
Save drodsou/45e9125f7cdec94e410582f659d27adb to your computer and use it in GitHub Desktop.
Like Object.assign but recursive and cloning arrays, not linking them
This file contains 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
// --------------------------------------------------------------------- | |
// javascript | |
// Like Object.assign but recursive and cloning arrays, not linking them | |
// --------------------------------------------------------------------- | |
function mergeDeep(/* obj1, obj2, ...*/) { | |
const isObject = (o)=>o && o !== undefined && o !== null && typeof o === 'object' && !Array.isArray(o) | |
let output = {} | |
Object.keys(arguments).forEach( a=>{ | |
let o = arguments[a] | |
if (!isObject(o)) throw 'mergeDeep: ERROR: all arguments must be objects' | |
Object.keys(o).forEach(key=>{ | |
if (!isObject(o[key])) { | |
if (Array.isArray(o[key])) output[key] = o[key].slice(0) // arrays: cloned and replaced (items not merged) | |
else output[key] = o[key] // numbers and strings: cloned; functions: linked | |
} else { | |
if (!output[key] || !isObject(output[key])) output[key] = {} // ensure dest is object | |
output[key] = mergeDeep(output[key],o[key]) // recurse | |
} | |
}) | |
}) | |
return output; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment