What you're building
A function getPath(obj, path) that safely reads a value from a deeply nested
object using a dot-and-bracket notation path string.
const data = { user: { address: { city: "Boston" }, scores: [10, 20, 30] } };
getPath(data, "user.address.city"); // "Boston"
getPath(data, "user.scores[1]"); // 20
getPath(data, "user.missing.field"); // undefined
Tools like Lodash _.get, MongoDB projections, and JSON Schema all rely on
this concept. It is also a common interview question at every level.
Requirements
- Support dot-separated keys:
"a.b.c" - Support bracket-indexed array access:
"items[0]"or"a.items[2].name" - Return
undefined(not an error) when any segment is missing or the parent is not an object - Index values in brackets will always be non-negative integers in the tests
Stretch goals
- Support negative indices:
"list[-1]"retrieves the last element - Support a default value as a third argument:
getPath(obj, path, defaultVal) - Support bracket-style string keys:
"map['key']"
What this proves
- You can tokenise and traverse arbitrary nested structures
- Safe property access and graceful handling of nullish values
- You understand how utility libraries implement their "get" helpers
β‘ 50 XP
solution.jsRuns in your browser
Loading editorβ¦
Tests4 to pass
dot-separated nested key
bracket array index
mixed dot and bracket
missing path returns undefined
Run your code to check these.