21.7. Deep map and deep omit
Topics
This question is in
21. Recursion and nested dataTwo jobs come up again and again with nested data. One is changing every value while keeping the shape: trimming every string in a form, turning every ISO string into a Date, masking every value before it is logged. The other is removing a field wherever it appears: password before a user object is sent to the client, __typename from a GraphQL response, internal ids before a snapshot.
Write both in deep-map-omit.js. deepMapValues(value, fn) returns a copy with the same shape, where every leaf is replaced by fn(leaf, path). deepOmit(value, keys) returns a copy without the listed keys, at every depth.
Signature
function deepMapValues(value, fn) // returns the mapped copy
function deepOmit(value, keys) // returns the copyvalue: any value. It is never changed.fn(leaf, path): called once per leaf.pathis an array of the keys from the top down to the leaf: strings for object keys, numbers for array indexes. Its return value takes the leaf's place.keys: an array of key names to remove.
A container is an array or a plain object (prototype Object.prototype or null). Everything else is a leaf: numbers, strings, null, undefined, Dates, Maps, class instances, functions.
Requirements
deepMapValues:
- Every leaf, at every depth, is replaced by
fn(leaf, path). Containers keep their shape: arrays stay arrays, with the same length and the same holes (fnis not called for a hole). pathlists the keys down to the leaf, with numbers for array indexes. Only a real index ("0","12") becomes a number; any other own key of an array, such as"label"or"01", stays a string, and its field is copied like an index's. Each call gets its own new array.fnis never called for a container. Empty objects and arrays stay empty.- A top-level leaf is mapped too:
deepMapValues(5, fn)returnsfn(5, []). fnis called depth first, inObject.keysorder.- An object used in two places is mapped in both places.
deepOmit:
- Every listed key is removed from every plain object, at every depth, including objects inside arrays.
- Array items are never removed, even if an index such as
"0"is listed. - With no matching keys, the result is an equal copy.
- Leaves are put in the copy as they are: a
Mapkeeps all of its entries. - A removed key's value is not walked at all.
Both:
- The result is a new structure: no container is shared with the input, and the input is not changed. Copies of containers are arrays and ordinary objects (prototype
Object.prototype). - A container that contains itself, among the values that are walked, throws a
TypeError. - An own key named
__proto__(asJSON.parsecreates) is copied as an ordinary key: it never changes a prototype.
Examples
deepMapValues({ price: 10, items: [1, 2] }, (n) => n * 2);
// { price: 20, items: [2, 4] }
deepMapValues({ user: { tags: ["a"] } }, (leaf, path) => path.join("."));
// { user: { tags: ["user.tags.0"] } }deepOmit(
{ id: 1, password: "x", friends: [{ id: 2, password: "y" }] },
["password"],
);
// { id: 1, friends: [{ id: 2 }] }deepOmit({ list: ["a", "b"] }, ["0"]); // { list: ["a", "b"] }Environment
- Plain JavaScript in a browser page; the tests call the globals
deepMapValuesanddeepOmitfromdeep-map-omit.js. - Only own, enumerable string keys are walked and copied (
Object.keys). Symbol keys are out of scope.
Hints
- Both functions are the same walk with a different rule at one point. Which point?
- What does each recursive call of
deepMapValuesneed to receive so thatfngets the right path? - What does
copy["__proto__"] = valuedo?
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