Created
May 16, 2017 23:29
-
-
Save iamvanja/cb4deb04c053ae6f763d86eeb7b967ca to your computer and use it in GitHub Desktop.
Deep object merge
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
export function isObject(item) { | |
return (item && typeof item === 'object' && !Array.isArray(item) && item !== null); | |
} | |
export default function mergeDeep(target, source) { | |
let output = Object.assign({}, target); | |
if (isObject(target) && isObject(source)) { | |
Object.keys(source).forEach(key => { | |
if (isObject(source[key])) { | |
if (!(key in target)) { | |
Object.assign(output, { [key]: source[key] }); | |
} | |
else { | |
output[key] = mergeDeep(target[key], source[key]); | |
} | |
} | |
else { | |
Object.assign(output, { [key]: source[key] }); | |
} | |
}); | |
} | |
return output; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment