Created
March 28, 2018 21:05
-
-
Save dmitrymatveev/056c75d232b3c4a684d061110412e4ee to your computer and use it in GitHub Desktop.
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 deepMerge(...objects) { | |
let dest = objects[0]; | |
let target = objects[1] || {}; | |
for(let targetKey of Object.keys(target)) { | |
let targetValue = target[targetKey]; | |
if (Array.isArray(targetValue)) { | |
dest[targetKey] = dest[targetKey] || []; | |
dest[targetKey].push(...targetValue); | |
} | |
else if (typeof targetValue === 'object' && targetValue) { | |
dest[targetKey] = merge(dest[targetKey] || {}, targetValue); | |
} | |
else { | |
dest[targetKey] = targetValue; | |
} | |
} | |
return objects.length > 2 ? | |
merge(dest, ...objects.slice(2)) : | |
dest; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment