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
undefinedstill 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 changeObject.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
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 10. ⌘Enter runs, ⌘⇧Enter submits.