30 seconds of code

  Back to Home



Creates a new object from the combination of two or more objects.

Use Array.prototype.reduce() combined with Object.keys(obj) to iterate over all objects and keys. Use hasOwnProperty() and Array.prototype.concat() to append values for keys existing in multiple objects.

const merge = (...objs) =>
    (acc, obj) =>
      Object.keys(obj).reduce((a, k) => {
        acc[k] = acc.hasOwnProperty(k) ? [].concat(acc[k]).concat(obj[k]) : obj[k];
        return acc;
      }, {}),