Deep merge objects

JavaScript, Object, Function · Jul 25, 2021

Deeply merges two objects, using a function to handle keys present in both.

  • Use Object.keys() to get the keys of both objects, create a Set from them and use the spread operator (...) to create an array of all the unique keys.
  • Use Array.prototype.reduce() to add each unique key to the object, using fn to combine the values of the two given objects.
const deepMerge = (a, b, fn) =>
  [ Set([...Object.keys(a), ...Object.keys(b)])].reduce(
    (acc, key) => ({ ...acc, [key]: fn(key, a[key], b[key]) }),
  { a: true, b: { c: [1, 2, 3] } },
  { a: false, b: { d: [1, 2, 3] } },
  (key, a, b) => (key === 'a' ? a && b : Object.assign({}, a, b))
// { a: false, b: { c: [ 1, 2, 3 ], d: [ 1, 2, 3 ] } }

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub or Twitter.

More like this

  • Map object keys

    JavaScript, Object

    Maps the keys of an object using the provided function, generating a new object.

  • Map object values

    JavaScript, Object

    Maps the values of an object using the provided function, generating a new object with the same keys.

  • Map an object to an array

    JavaScript, Object

    Maps an object to an object array, using the provided mapping function.