CodeNot attempted
getByPath (lodash.get)
Difficulty: easy
getByPath(obj, 'a.b[0].c', defaultValue), also accepting an array path like ['a', 'b', 0, 'c'].
- return
defaultValueonly when the result isundefined(nulland0are real values) - never throw on
null/undefinedalong the way - an empty path returns the object itself
Bonus: infer the return type from the string path with template literal types.
Show reference solution
export function getByPath(obj: unknown, path: string | readonly (string | number)[], defaultValue?: unknown): any { let keys: readonly (string | number)[]; if (typeof path === 'string') { // "a.b[0].c" → ["a", "b", "0", "c"] keys = path.replaceAll('[', '.').replaceAll(']', '').split('.').filter((key) => key !== ''); } else { keys = path; }
let current: any = obj; for (const key of keys) { if (current === null || current === undefined) { return defaultValue; } current = current[key]; } if (current === undefined) { return defaultValue; } return current;}
Ctrl Enter