Skip to content
Onsite

Deep Merge

MediumP2Coding

Implement deepMerge(...objects), which merges any number of objects from left to right into a new object.

  • Keys that exist in only one object are copied.
  • When a key exists in several objects: if both values are plain objects, merge them recursively; otherwise the value from the later object wins.
  • Arrays are not merged: an array from a later object replaces the earlier value.
  • A key whose later value is undefined still overrides (it is a real value).
  • The inputs are never modified, and nested plain objects in the result are fresh copies, so changing the result does not change an input.
  • Own enumerable string keys only. The key "__proto__" must be ignored, so merging untrusted JSON cannot change Object.prototype.

A plain object is one created by {}, Object.create(null) or JSON.parse. Dates, class instances and other objects are treated as ordinary values (later wins, copied by reference).

Example 1

Input
deepMerge({ a: 1, b: { c: 2, d: 3 } }, { b: { c: 9 }, e: 4 })
Output
{ a: 1, b: { c: 9, d: 3 }, e: 4 }

Constraints

  • Total number of keys <= 10^4
  • No circular references.

Hints

Run checks the 3 visible tests, Submit all 10.