Skip to content

Instantly share code, notes, and snippets.

@Juknum
Last active November 16, 2021 00:01
Show Gist options
  • Save Juknum/0745334cd73e38077e45b46065e0841a to your computer and use it in GitHub Desktop.
Save Juknum/0745334cd73e38077e45b46065e0841a to your computer and use it in GitHub Desktop.
Object.merge(target, ...sources) : Deep merge for JS Objects
/** https://gist.github.com/Juknum/6750c0ec3a4249359b5be0641185f917 => Object.isObject(object) */
Object.defineProperty(Object.prototype, 'merge', {
/**
* @param {Object} target
* @param {...Object} sources
*/
value: (target, ...sources) => {
if (!sources.length) return target
const source = sources.shift()
if (Object.isObject(target) && Object.isObject(source)) {
for (const key in source) {
if (Object.isObject(source[key])) {
if (!target[key]) Object.assign(target, { [key]: {} })
Object.merge(target[key], source[key])
}
else Object.assign(target, { [key]: source[key] })
}
}
return Object.merge(target, ...sources)
}
})
/**
* Example:
* const target = { a: { b: 'overwritten' }, b: { m: 2 }, c: { n: { y: 'a' } } }
* const obj = { a: 0, b: { n: 1 }, c: { n: { z: 'b' } } }
* const obj2 = { d: 5 }
* console.log(Object.merge(target, obj, obj2))
* => expected output: { a: 0, b: { m: 2, n: 1 }, c: { n: { y: 'a', z: 'b' } } }
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment