Skip to content

Instantly share code, notes, and snippets.

@wonderbeyond
Last active May 26, 2023 05:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wonderbeyond/eb21b451a46ef711bd2b165a1a4b71c5 to your computer and use it in GitHub Desktop.
Save wonderbeyond/eb21b451a46ef711bd2b165a1a4b71c5 to your computer and use it in GitHub Desktop.
[javascript] deep merge objects
/**
* 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