Created
June 3, 2016 10:04
-
-
Save mhingston/cbfb9e36af72effcb50ae40a11f9e294 to your computer and use it in GitHub Desktop.
Deeply merge 2 objects, i.e. deep Object.assign
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
const mergeObjects = (target, source) => | |
{ | |
const isObject = item => item && typeof item === "object" && !Array.isArray(item) && item !== null | |
if(isObject(target) && isObject(source)) | |
{ | |
for(let key in source) | |
{ | |
if(source.hasOwnProperty(key) && isObject(source[key])) | |
{ | |
if(!target.hasOwnProperty(key)) | |
{ | |
target[key] = {} | |
} | |
mergeObjects(target[key], source[key]) | |
} | |
else | |
{ | |
target[key] = source[key] | |
} | |
} | |
} | |
return target | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment