Skip to curriculum
Jump to the editor

21.11. Get a value by path

Easy
Topics
10–20 min

Reading deep data by hand is fragile: response.data.user.address.city throws a TypeError as soon as address is missing. Optional chaining (?.) fixes that in code you write by hand, but many paths are only known at run time: a column definition that says which field to show, a form field bound to "shipping.address.zip", a sort key chosen by the user. For those you need a function that follows a path given as data.

Write getPath(object, path, defaultValue) in get-path.js. It follows the path one key at a time and returns what it finds, or defaultValue when there is nothing there.

Signature

JAVASCRIPT
function getPath(object, path, defaultValue) // returns the value found, or defaultValue
  • object: any value. It is never changed.
  • path: a string such as "friends[0].name", an array of keys such as ["friends", 0, "name"], or a single number.
  • defaultValue: returned when the result would be undefined. Leaving it out means undefined.

Requirements

  1. A string path is split into keys at ., [ and ], and empty keys are dropped: "a.b[0].c", "a.b.0.c" and "a.b[0]c" all mean a, b, 0, c. "grid[1][0]" and "[0].name" work too.
  2. An array path is used as it is: its keys may contain dots, and may be numbers or symbols. A number path is one key. The path array is not changed.
  3. Each step is an ordinary property read, so inherited properties and the properties of strings ("word.length") are found.
  4. If a step meets null or undefined, the walk stops and returns defaultValue. Nothing throws.
  5. A final value of undefined gives defaultValue. Every other value is returned as it is, including null, 0, "", false and NaN.
  6. Everything except ., [ and ] belongs to a key: "first name" is one key, and "2024.total" reads key "2024".
  7. An empty path ("" or []) returns object itself, or defaultValue if object is undefined.
  8. The object is not changed.

Examples

JAVASCRIPT
const user = { name: "Ada", friends: [{ name: "Grace" }], address: null };

getPath(user, "friends[0].name");          // "Grace"
getPath(user, ["friends", 0, "name"]);     // "Grace"
getPath(user, "friends.5.name", "nobody"); // "nobody"
JAVASCRIPT
getPath(user, "address.city", "unknown"); // "unknown" (address is null)
getPath(user, "address", "unknown");      // null (null is a real value)
getPath({ count: 0 }, "count", 10);       // 0
JAVASCRIPT
getPath({ "a.b": 1 }, ["a.b"]); // 1
getPath({ "a.b": 1 }, "a.b");   // undefined: the string means key "a", then key "b"

Environment

  • Plain JavaScript in a browser page; the tests call the global getPath from get-path.js.
  • Quoted keys inside brackets (a["b.c"]) are out of scope: use an array path for keys with dots.

Hints

  1. Which single string method can split "a.b[0].c" at all three separators?
  2. What does result || defaultValue do when the result is 0?

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…