Skip to content

Instantly share code, notes, and snippets.

@metavoid
Last active February 10, 2019 21:29
Show Gist options
  • Select an option

  • Save metavoid/774dbdf7196e133777bde80d1290bb8f to your computer and use it in GitHub Desktop.

Select an option

Save metavoid/774dbdf7196e133777bde80d1290bb8f to your computer and use it in GitHub Desktop.
Deep merge JS objects (unlike shallow merge of Object.assign and else)
//Recursive deep merge JS objects (unlike shallow merge of Object.assign and else)
function deepMerge(target, source) {
let output = Object.assign({}, target);
if (this.isObject(target) && this.isObject(source)) {
Object.keys(source).forEach(key => {
if (this.isObject(source[key])) {
if (!(key in target))
Object.assign(output, {
[key]: source[key]
});
else output[key] = this.deepMerge(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