Last active
August 15, 2017 09:35
-
-
Save gilankpam/81f3be9bdf700870ebbd6a9c85a5a184 to your computer and use it in GitHub Desktop.
Javascript Deep Merge (Recursive)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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