Skip to content

Instantly share code, notes, and snippets.

@ghostcode
Forked from ahtcx/deep-merge.js
Created June 8, 2022 07:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ghostcode/0365197c33a52fb07591e3b273ef5996 to your computer and use it in GitHub Desktop.
Save ghostcode/0365197c33a52fb07591e3b273ef5996 to your computer and use it in GitHub Desktop.
Deep-Merge JavaScript objects with ES6
// ⚠ IMPORTANT: this is old and doesn't work for many different edge cases but I'll keep it as-is for any of you want it
// ⚠ IMPORTANT: you can find more robust versions in the comments or use a library implementation such as lodash's `merge`
// Merge a `source` object to a `target` recursively
const merge = (target, source) => {
// Iterate through `source` properties and if an `Object` set property to merge of `target` and `source` properties
for (const key of Object.keys(source)) {
if (source[key] instanceof Object) Object.assign(source[key], merge(target[key], source[key]))
}
// Join `target` and modified `source`
Object.assign(target || {}, source)
return target
}
const merge=(t,s)=>{const o=Object,a=o.assign;for(const k of o.keys(s))s[k]instanceof o&&a(s[k],merge(t[k],s[k]));return a(t||{},s),t}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment