Created
September 2, 2019 20:39
-
-
Save ScriptedAlchemy/25be43bfb45baaf047a7991de4b64127 to your computer and use it in GitHub Desktop.
Immutable Deep merge
This file contains 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
function mergeDeep(...objects) { | |
const isObject = obj => obj && typeof obj === 'object'; | |
return objects.reduce((prev, obj) => { | |
Object.keys(obj).forEach(key => { | |
const pVal = prev[key]; | |
const oVal = obj[key]; | |
if (Array.isArray(pVal) && Array.isArray(oVal)) { | |
prev[key] = pVal.concat(...oVal); | |
} | |
else if (isObject(pVal) && isObject(oVal)) { | |
prev[key] = mergeDeep(pVal, oVal); | |
} | |
else { | |
prev[key] = oVal; | |
} | |
}); | |
return prev; | |
}, {}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment