Data Helper 1: Get Value by Path
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 — 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.
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'); // => undefinedSolution
Overview
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.
Approach: Iterative traversal with "missing" detection (recommended)
Algorithm:
- Normalize the path to an array of segments (split dots if needed).
- Start with
cur = objand iterate through segments. - If
curis nullish at any point, return the fallback. - Use
Object.prototype.hasOwnProperty.call(cur, seg)(orseg in cur) to check existence. If missing, return fallback. - Otherwise set
cur = cur[seg]and continue. - If all segments resolve, return
cureven if it is falsy.
Complexity: O(k) time, O(k) space for path normalization.
function toSegments(path) {
if (Array.isArray(path)) return path;
if (typeof path !== 'string') return null;
const s = path.trim();
if (!s) return [];
return s.split('.');
}
export default function getByPath(obj, path, fallback) {
const segs = toSegments(path);
if (!segs) return fallback;
let cur = obj;
for (let i = 0; i < segs.length; i++) {
const seg = segs[i];
if (cur === null || cur === undefined) {
return fallback;
}
// allow numeric indexing when segment is number or numeric string
const key = typeof seg === 'number' ? seg : seg;
// Only treat as missing when key is not present
if (typeof cur === 'object' || typeof cur === 'function') {
if (!(key in cur)) return fallback;
cur = cur[key];
} else {
return fallback;
}
}
return cur;
}
function toSegments(path: string | Array<string | number>): Array<string | number> | null {
if (Array.isArray(path)) return path;
if (typeof path !== 'string') return null;
const s = path.trim();
if (!s) return [];
return s.split('.');
}
export default function getByPath(
obj: any,
path: string | Array<string | number>,
fallback?: any
): any {
const segs = toSegments(path);
if (!segs) return fallback;
let cur: any = obj;
for (let i = 0; i < segs.length; i++) {
const seg = segs[i];
if (cur === null || cur === undefined) {
return fallback;
}
const key: any = seg;
if (typeof cur === 'object' || typeof cur === 'function') {
if (!(key in cur)) return fallback;
cur = cur[key];
} else {
return fallback;
}
}
return cur;
}
Notes & Pitfalls
Using || fallbackwhich incorrectly replaces valid values likefalse/0/''.Not handling arrays ( items.0.name).Throwing when a mid-level object is null/undefined.
Empty path ( ''or[]) should return the object itself.Value exists but is undefined(property present with value undefined). This should returnundefined, not fallback (because it exists).Path passed as array with numeric segments.
Path normalization (string -> segments) Safe iterative traversal Use into distinguish missing vs falsy
Common mistakes on this challenge
getByPath traversal or fallback behavior is inconsistent
This helper must distinguish missing keys from existing keys whose value is undefined. Normalize path into segments and short-circuit empty path by returning input object. At each segment, return fallback only when key is missing or traversal hits nullish intermediate. If key exists and value is undefined, returnundefined(do not replace with fallback).
Resources
Similar questions
Guides
Preparing for interviews? Use Frontend Coding Challenges first, then move into a concrete Study Plan before targeted Company Prep.
Built in public
The code behind FrontendAtlas lives on GitHub. A star helps other frontend engineers find it.