21.12. Set a value by path, creating what is missing
Topics
This question is in
21. Recursion and nested dataForm libraries, config editors and state stores often update a value deep inside an object by its path: "shipping.address.zip", "items[2].quantity". When the containers on the way do not exist yet, they have to be created, and the right kind matters: items[2] needs an array, address an object. Because these paths often come from user input (field names, query strings, JSON), a path setter is also one of the most common ways to pollute Object.prototype: a path like "__proto__.isAdmin" would make every object in the page look like an admin.
Write setPath(object, path, value) in set-path.js. It writes value at path, creates what is missing, changes object in place and returns it, and refuses any path that could reach a prototype.
Signature
function setPath(object, path, value) // returns objectobject: the object or array to write into. It is changed in place.path: a string such as"items[0].name", an array of keys such as["items", 0, "name"], or a single number.value: any value,undefinedincluded.
Requirements
- A string path is split into keys at
.,[and], dropping empty keys. An array path is used as it is (keys may contain dots, or be numbers or symbols). A number path is one key. - The value is assigned at the last key, replacing whatever was there. The function returns the same
object. - Every key before the last leads into a container. If the object owns a value there that can hold properties (an object, an array, a Date, a function), the walk goes into it, and its other keys are kept.
- Otherwise (nothing there, an inherited value such as
toString,null, or a primitive), a new container is put there first: an array when the next key is an index, an object otherwise. - An index is a whole number
≥ 0, or a string of digits without a leading zero ("0","12")."01","-1"and1.5are ordinary keys. - Writing past the end of an existing array extends it and leaves holes.
- If any key of the path is
__proto__,constructororprototype,setPaththrows aTypeError, and nothing at all is written, not even the containers before that key. - An empty path, or an
objectthat is not an object, array or function, throws aTypeError. - Keys such as
hasOwnPropertyare ordinary data, and objects with anullprototype work.
Examples
const state = { user: { name: "Ada" } };
setPath(state, "user.address.city", "London");
// state is { user: { name: "Ada", address: { city: "London" } } }setPath({}, "items[1].qty", 2); // { items: [ <hole>, { qty: 2 } ] }
setPath({}, ["a.b", "c"], 1); // { "a.b": { c: 1 } }
setPath({ a: 5 }, "a.b", 1); // { a: { b: 1 } }setPath({}, "__proto__.isAdmin", true); // throws TypeError
setPath({}, "constructor.prototype.isAdmin", true); // throws TypeError
({}).isAdmin; // undefinedEnvironment
- Plain JavaScript in a browser page; the tests call the global
setPathfromset-path.js. - Quoted keys in brackets (
a["b.c"]) are out of scope: use an array path. - Maps on the path are treated like any other object (their properties, not their entries).
Hints
- When a step has to create a container, which key decides whether it is an array or an object: this one or the next?
- A fresh
{}has no ownconstructor, but({}).constructoris still something. What is it, and what is itsprototype? - Why check the whole path before writing the first container?
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