Skip to content

Instantly share code, notes, and snippets.

@zortext
Forked from Salakar/deepMerge.md
Last active September 22, 2018 08:06
Show Gist options
  • Save zortext/7e37142a91c9abfcc641f6e2dc306235 to your computer and use it in GitHub Desktop.
Save zortext/7e37142a91c9abfcc641f6e2dc306235 to your computer and use it in GitHub Desktop.
ES6/ES2015 Object deep merge

Deep Merge

Quick function to deep merge using Object.assign(). Thoughts?

    /**
     * Simple is object check.
     * @param item
     * @returns {boolean}
     */
    export function isObject(item) {
      return (item && typeof item === 'object' && !Array.isArray(item) && item !== null  && !(item instanceof Map));
    }
    
    /**
     * Deep merge two objects.
     * @param target
     * @param source
     */
    export function mergeDeep(target, source) {
      if (isObject(target) && isObject(source)) {
        Object.keys(source).forEach(key => {
          if (isObject(source[key])) {
            if (!target[key]) Object.assign(target, { [key]: {} });
            mergeDeep(target[key], source[key]);
          } else {
            Object.assign(target, { [key]: source[key] });
          }
        });
      }
      return target;
    }

###Example usages:

    mergeDeep(this, { a: { b: { c: 123 } } });
    // or
    const merged = mergeDeep({a: 1}, { b : { c: { d: { e: 12345}}}});  
    console.dir(merged); // { a: 1, b: { c: { d: [Object] } } }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment