Skip to content

Instantly share code, notes, and snippets.

@drodsou
Last active July 30, 2016 09:03
Show Gist options
  • Save drodsou/45e9125f7cdec94e410582f659d27adb to your computer and use it in GitHub Desktop.
Save drodsou/45e9125f7cdec94e410582f659d27adb to your computer and use it in GitHub Desktop.
Like Object.assign but recursive and cloning arrays, not linking them
// ---------------------------------------------------------------------
// 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