AniUI Academy

Read a nested value by dotted path

mediumArrays & Objects+250 XPPractice

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 to null.

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 survive

What it has to do

  • Split the path on dots and follow each segment in turn.
  • Read numeric segments as array indices.
  • Return fallback instead of throwing when a segment cannot be followed.
  • Default fallback to null when it is not supplied.
  • Return genuine falsy values such as 0 and false rather than the fallback.
Asked atMeta

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +250 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.