Skip to content

Instantly share code, notes, and snippets.

@rpivo
Last active March 2, 2021 22:56
Show Gist options
  • Save rpivo/f11ee6492ae4c9cfc4e0697351b44786 to your computer and use it in GitHub Desktop.
Save rpivo/f11ee6492ae4c9cfc4e0697351b44786 to your computer and use it in GitHub Desktop.
Deeply Merge Objects with Recursive Reduce in JavaScript

Deeply Merge Objects with Recursive Reduce in JavaScript

function recursiveMerge(...objects) {
  function byMerger(newObj, obj) {
    if (!Object.keys(newObj).length) return obj

    for (const [key, value] of Object.entries(obj)) {
      if (newObj[key] && typeof newObj[key] !== 'string' && Object.keys(newObj[key]).length)
        newObj[key] = recursiveMerge(newObj[key], value)

      else newObj[key] = value
    }

    return newObj
  }

  return objects.reduce(byMerger, {})
}

const obj1 = {
  a: 'hello',
  d: null,
  f: { foo: 'bar' }
}

const obj2 = {
  a: 'goodbye',
  b: 'hello again',
  e: undefined,
  f: { hey: 'there' }
}

const obj3 = {
  b: 'goodbye again',
  c: 'hello hello'
}

console.log(
  recursiveMerge(obj1, obj2, obj3)
)

Returns:

{
  a: 'goodbye',
  d: null,
  f: { foo: 'bar', hey: 'there' },
  b: 'goodbye again',
  e: undefined,
  c: 'hello hello'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment