Data Helper 1: Get Value by Path

intermediate
By FrontendAtlas Editorial · Updated Oct 10, 2026
Implement getByPath(obj, path, fallback?) that safely reads a nested value from an object. This is extremely common in frontend screens (reading deep API responses, feature flags, form state) and shows up often in interviews. Path rules: - path can be a dot string: "a.b.c" - or an array of keys: ["a", "b", "c"] - Numeric segments should work for arrays: "items.0.name". Requirements: 1) If the full path exists, return the value (even if it is null, false, or 0). 2) If any segment is missing, return fallback (or undefined if not provided). 3) Must not throw for nullish intermediate values. 4) No eval, no JSON stringify tricks. This tests safe traversal + edge-case correctness.

Arguments

  • obj: any — The object/array to read from.
  • path: string | (string | number)[] — Path as dot string or array of segments.
  • fallback: any — Optional value to return when the path does not exist.

Returns

any — The found value, or fallback/undefined when missing.

Solution idea

Traverse an object safely by path segments and return either the value or a fallback. The crucial detail is to distinguish missing properties from valid falsy values like 0, false, or ''. This makes the helper reliable for real-world API data and UI state.

Examples
const data = { user: { profile: { name: 'Ada' }, flags: { pro: false } }, items: [{ name: 'x' }] };

getByPath(data, 'user.profile.name'); // => 'Ada'
getByPath(data, ['user', 'flags', 'pro']); // => false
getByPath(data, 'items.0.name'); // => 'x'
getByPath(data, 'user.profile.age', 18); // => 18
getByPath(data, 'missing.anything'); // => undefined