FrontendInterviews.dev

Loading problem…

281. Lodash `get`

Easyβ€’

Implement a get(object, path, defaultValue) function similar to Lodash's _.get().

It safely accesses deeply nested properties without throwing errors when intermediate values are null or undefined.

Requirements

1. Core Behavior

  • path can be a string like 'a.b.c' or 'a[0].b'
  • path can also be an array like ['a', 'b', 'c']
  • Return the value at the path, or defaultValue if the resolved value is undefined

2. Path Parsing

  • Dot notation: 'a.b.c' β†’ keys ['a', 'b', 'c']
  • Bracket notation: 'a[0].b' β†’ keys ['a', '0', 'b']
  • Mixed: 'a.b[0].c' β†’ keys ['a', 'b', '0', 'c']
  • Array path: ['a', '0', 'b'] β†’ keys used directly

3. Edge Cases

  • null or undefined as the object β†’ return defaultValue
  • null in the path β†’ return defaultValue (can't traverse further)
  • Value is null β†’ return null (not the default)
  • Value is undefined β†’ return defaultValue
  • Value is 0, false, '' β†’ return the value (not the default)

Example Usage

const obj = { a: { b: [{ c: 42 }] } };

get(obj, 'a.b[0].c');        // 42
get(obj, 'a.b[0].d', 'N/A'); // 'N/A'
get(obj, ['a', 'b', '0']);   // { c: 42 }
get(null, 'a.b', 'default'); // 'default'

Real-World Context

  • API response handling: Safely accessing nested API data without ?. chains
  • Configuration objects: Accessing deeply nested config with fallback defaults
  • Form state: Accessing nested form values like 'address.city' in React Hook Form

Constraints

  • Must handle both string and array paths
  • Must parse bracket notation in string paths
  • Must return defaultValue only when resolved value is undefined
  • Must not throw on null/undefined intermediate values
Accepted7/10|Acceptance Rate70.0%