Deep Merging JavaScript Objects


The JavaScript code to merge objects syntax highlighted. See the actual text below in the post

Deep merging objects in JavaScript is a bit tricky. Here’s one solution; there are many many others. While this was fun to write, you’ll probably want to go use the merge function in lodash instead. None the less here’s some code golf

function merge(...sources) {
  return sources.reduce((target, source) => {  // enumerate the sources
    return Object.entries(source).reduce((result, [key, value]) => {  // enumerate the properties
      if(Array.isArray(value)) {
        if(Array.isArray(result[key])) {
          result[key] = result[key].concat(value); // got two arrays, merge them
        } else {
          result[key] = value;  // clobber it, either undefined or not an array
        }
      } else if(value === Object(value)) {
        if(result[key] === Object(result[key])) {
          result[key] = merge(result[key], value); // two objects, recurse and merge them
        } else {
          result[key] = merge(value); // recurse and clobber it, either undefined or not an object
        }
      } else {
        result[key] = value;  // must be a primitive, clobber it
      }
      return result;
    }, target);
  }, {});
}

Advertisement

No Comments

Name
A name is required.
Email
An email is required.
Site
Invalid URL

No comments yet