Skip to curriculum
Jump to the editor

21.6. Deep merge

Medium
Topics
20–35 min

Settings usually come in layers: defaults shipped with the app, then the team's settings, then the user's own. Each layer only names what it changes, often several levels down (theme.colors.accent). Spreading the layers ({ ...defaults, ...user }) replaces theme as a whole and loses every color the user did not mention. A deep merge combines the layers key by key, at every depth.

Write deepMerge(...sources) in deep-merge.js. It returns a new object built from the sources, left to right. Plain objects found under the same key are merged; anything else from a later source replaces what was there. Because merge functions often receive parsed JSON from outside, it must not let a __proto__ or constructor.prototype key reach Object.prototype.

Signature

JAVASCRIPT
function deepMerge(...sources) // returns a new object
  • sources: any number of objects, merged from left to right. None of them is changed.
  • Returns a new plain object.

Requirements

  1. The result is a new object, even with one source ({} with none). It shares no plain object or array with any source: changing the result never changes a source.
  2. For the same key, a later source wins.
  3. When the result already holds a plain object under a key and the next source also has a plain object there, the two are merged, at any depth.
  4. Arrays are not merged: an array from a later source replaces the old value. Arrays are copied, together with the plain objects and arrays inside them.
  5. A source value of undefined is skipped (the old value stays). null, 0, "", false and NaN are real values and overwrite.
  6. When the old and the new value are not both plain objects (a number and an object, an object and an array…), the new value replaces the old.
  7. Only plain objects (prototype Object.prototype or null) are merged and copied. A Date, Map, Set, class instance or function is put in the result as it is.
  8. Arguments that are not plain objects (null, undefined) are skipped.
  9. A key named __proto__ is skipped at every depth: it never changes a prototype and never reaches Object.prototype. A constructor.prototype payload must not reach Object.prototype either.
  10. Keys such as hasOwnProperty are ordinary data.
  11. A source that contains itself (an object or an array inside itself) throws a TypeError.
  12. The sources are not changed.

Examples

JAVASCRIPT
deepMerge(
  { theme: { color: "blue", size: 12 }, plugins: ["a", "b"] },
  { theme: { color: "red" }, plugins: ["c"] },
);
// { theme: { color: "red", size: 12 }, plugins: ["c"] }
JAVASCRIPT
deepMerge({ a: 1, b: 2 }, { a: undefined, b: null }); // { a: 1, b: null }
deepMerge({ a: { x: 1 } }, { a: 5 });                 // { a: 5 }
JAVASCRIPT
deepMerge({}, JSON.parse('{"__proto__": {"admin": true}}'));
({}).admin; // undefined

Environment

  • Plain JavaScript in a browser page; the tests call the global deepMerge from deep-merge.js.
  • Only own, enumerable string keys are merged (Object.keys). Symbol keys are out of scope.
  • Objects shared inside a source may become separate copies in the result.

Hints

  1. If the result only ever holds objects that deepMerge created itself, which objects is it safe to write into?
  2. What does result["__proto__"] = value do on an ordinary object?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…