Skip to curriculum
Jump to the editor

21.12. Set a value by path, creating what is missing

Medium
Topics
20–35 min

Form 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

JAVASCRIPT
function setPath(object, path, value) // returns object
  • object: 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, undefined included.

Requirements

  1. 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.
  2. The value is assigned at the last key, replacing whatever was there. The function returns the same object.
  3. 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.
  4. 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.
  5. An index is a whole number ≥ 0, or a string of digits without a leading zero ("0", "12"). "01", "-1" and 1.5 are ordinary keys.
  6. Writing past the end of an existing array extends it and leaves holes.
  7. If any key of the path is __proto__, constructor or prototype, setPath throws a TypeError, and nothing at all is written, not even the containers before that key.
  8. An empty path, or an object that is not an object, array or function, throws a TypeError.
  9. Keys such as hasOwnProperty are ordinary data, and objects with a null prototype work.

Examples

JAVASCRIPT
const state = { user: { name: "Ada" } };
setPath(state, "user.address.city", "London");
// state is { user: { name: "Ada", address: { city: "London" } } }
JAVASCRIPT
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 } }
JAVASCRIPT
setPath({}, "__proto__.isAdmin", true);              // throws TypeError
setPath({}, "constructor.prototype.isAdmin", true);  // throws TypeError
({}).isAdmin;                                        // undefined

Environment

  • Plain JavaScript in a browser page; the tests call the global setPath from set-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

  1. When a step has to create a container, which key decides whether it is an array or an object: this one or the next?
  2. A fresh {} has no own constructor, but ({}).constructor is still something. What is it, and what is its prototype?
  3. 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
Back to the question
Loading the editor…