Read a nested value by dotted path
Half-loaded API responses are the normal case, not the exception. Reaching into one blindly throws "cannot read property of undefined" — and optional chaining does not help when the path itself is data, such as a column key in a config-driven table.
Implement getPath(source, path, fallback). path is a string of segments separated by dots, like "user.profile.name". Walk the segments in order, reading each one as a property. Numeric segments read array indices, so "items.0.id" works. If at any point the current value is null or undefined and there are still segments left, stop and return fallback. If the value you finally arrive at is undefined, also return fallback. fallback defaults to null when not supplied. Falsy values that genuinely exist, such as 0, false and "", are returned as they are, not replaced by the fallback.
Arguments
sourceany- The root value to walk into.
pathstring- A dot-separated path like
"user.profile.name"or"items.0.id". fallbackany- Returned when a segment cannot be followed or the final value is
undefined. Defaults tonull.
Returns
any — The value at the end of path, or fallback when the path cannot be fully followed.
Examples
getPath({ user: { profile: { name: "Ada" } } }, "user.profile.name");
// "Ada"getPath({ items: [{ id: 7 }] }, "items.0.id"); // 7 — numeric segments read indices
getPath({ a: 1 }, "a.b.c", "none"); // "none" — broken path yields fallback
getPath({ a: { b: 0 } }, "a.b", "fallback"); // 0 — real falsy values surviveWhat it has to do
- Split the path on dots and follow each segment in turn.
- Read numeric segments as array indices.
- Return
fallbackinstead of throwing when a segment cannot be followed. - Default
fallbacktonullwhen it is not supplied. - Return genuine falsy values such as
0andfalserather than the fallback.
Stuck? The javascript course covers everything this challenge needs.
- 1.reads a deeply nested property
- 2.reads through an array index
- 3.returns the fallback for a broken path
- 4.defaults the fallback to null
- 5.returns falsy values that really exist
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.