21.11. Get a value by path
Topics
This question is in
21. Recursion and nested dataReading 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
function getPath(object, path, defaultValue) // returns the value found, or defaultValueobject: 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 beundefined. Leaving it out meansundefined.
Requirements
- 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 meana,b,0,c."grid[1][0]"and"[0].name"work too. - 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.
- Each step is an ordinary property read, so inherited properties and the properties of strings (
"word.length") are found. - If a step meets
nullorundefined, the walk stops and returnsdefaultValue. Nothing throws. - A final value of
undefinedgivesdefaultValue. Every other value is returned as it is, includingnull,0,"",falseandNaN. - Everything except
.,[and]belongs to a key:"first name"is one key, and"2024.total"reads key"2024". - An empty path (
""or[]) returnsobjectitself, ordefaultValueifobjectisundefined. - The object is not changed.
Examples
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"getPath(user, "address.city", "unknown"); // "unknown" (address is null)
getPath(user, "address", "unknown"); // null (null is a real value)
getPath({ count: 0 }, "count", 10); // 0getPath({ "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
getPathfromget-path.js. - Quoted keys inside brackets (
a["b.c"]) are out of scope: use an array path for keys with dots.
Hints
- Which single string method can split
"a.b[0].c"at all three separators? - What does
result || defaultValuedo when the result is0?
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