Skip to content

Instantly share code, notes, and snippets.

@gilankpam
Last active August 15, 2017 09:35
Show Gist options
  • Save gilankpam/81f3be9bdf700870ebbd6a9c85a5a184 to your computer and use it in GitHub Desktop.
Save gilankpam/81f3be9bdf700870ebbd6a9c85a5a184 to your computer and use it in GitHub Desktop.
Javascript Deep Merge (Recursive)
// Merge multiple objects
function deepMerges(...objs) {
return objs.reduce((a, b) => deepMerge(a,b), {})
}
// Merge two objects
function deepMerge (one, two) {
if (Array.isArray(one) && Array.isArray(two)) {
return one.concat(two)
}
if (typeof two !== 'object' || typeof one !== 'object'|| one === undefined ) {
return two
}
if (typeof one === 'object' && typeof two === 'object') {
const newObj = Object.assign({}, one)
for (let key of Object.keys(two)) {
newObj[key] = deepMerge(newObj[key], two[key])
}
return newObj
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment