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.
What 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.
Your workspace
Ready to check it?
5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.
AI Crack & Solution Assist
Stuck? Get instant AI hints or break down the optimal solution.
Stuck? The javascript course covers everything this challenge needs.