Skip to content

Instantly share code, notes, and snippets.

@wonderbeyond
Last active May 26, 2023 05:41
Show Gist options
  • Select an option

  • Save wonderbeyond/eb21b451a46ef711bd2b165a1a4b71c5 to your computer and use it in GitHub Desktop.

Select an option

Save wonderbeyond/eb21b451a46ef711bd2b165a1a4b71c5 to your computer and use it in GitHub Desktop.

Revisions

  1. wonderbeyond created this gist May 26, 2023.
    29 changes: 29 additions & 0 deletions merge-deep.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,29 @@
    /**
    * 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;
    }, {});
    }