21.6. Deep merge
Topics
This question is in
21. Recursion and nested dataSettings 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
function deepMerge(...sources) // returns a new objectsources: any number of objects, merged from left to right. None of them is changed.- Returns a new plain object.
Requirements
- 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. - For the same key, a later source wins.
- 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.
- 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.
- A source value of
undefinedis skipped (the old value stays).null,0,"",falseandNaNare real values and overwrite. - 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.
- Only plain objects (prototype
Object.prototypeornull) are merged and copied. ADate,Map,Set, class instance or function is put in the result as it is. - Arguments that are not plain objects (
null,undefined) are skipped. - A key named
__proto__is skipped at every depth: it never changes a prototype and never reachesObject.prototype. Aconstructor.prototypepayload must not reachObject.prototypeeither. - Keys such as
hasOwnPropertyare ordinary data. - A source that contains itself (an object or an array inside itself) throws a
TypeError. - The sources are not changed.
Examples
deepMerge(
{ theme: { color: "blue", size: 12 }, plugins: ["a", "b"] },
{ theme: { color: "red" }, plugins: ["c"] },
);
// { theme: { color: "red", size: 12 }, plugins: ["c"] }deepMerge({ a: 1, b: 2 }, { a: undefined, b: null }); // { a: 1, b: null }
deepMerge({ a: { x: 1 } }, { a: 5 }); // { a: 5 }deepMerge({}, JSON.parse('{"__proto__": {"admin": true}}'));
({}).admin; // undefinedEnvironment
- Plain JavaScript in a browser page; the tests call the global
deepMergefromdeep-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
- If the result only ever holds objects that
deepMergecreated itself, which objects is it safe to write into? - What does
result["__proto__"] = valuedo 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