Last active
May 26, 2023 05:41
-
-
Save wonderbeyond/eb21b451a46ef711bd2b165a1a4b71c5 to your computer and use it in GitHub Desktop.
[javascript] deep merge objects
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
/** | |
* Performs a deep merge of objects and returns new object. Does not modify | |
* objects (immutable) and merges arrays via concatenation. | |
* | |
* @param {...object} objects - Objects to merge | |
* @returns {object} New object with merged key/values | |
*/ | |
export default 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