Skip to content

Instantly share code, notes, and snippets.

@dmitrymatveev
Created March 28, 2018 21:05
Show Gist options
  • Save dmitrymatveev/056c75d232b3c4a684d061110412e4ee to your computer and use it in GitHub Desktop.
Save dmitrymatveev/056c75d232b3c4a684d061110412e4ee to your computer and use it in GitHub Desktop.
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