Get Nested Value

MediumObjects15 min4 tests

Implement a get function (like Lodash's _.get) that safely retrieves a nested property from an object using a dot-notation path string.

Requirements

  • Support dot notation: "a.b.c"
  • Support bracket notation for arrays: "a[0].b"
  • Return a default value if the path doesn't exist

Example

const obj = { a: { b: [{ c: 42 }] } };
get(obj, 'a.b[0].c');        // 42
get(obj, 'a.x.y', 'default'); // 'default'
Hints (4)
  1. Normalize bracket notation [0] into dot notation .0 first.
  2. Split the path by . to get individual keys.
  3. Walk through the object one key at a time.
  4. Return the default value if you encounter null or undefined.

Topics

  • Objects

Asked at

Google · Amazon · Airbnb · Uber

Join Us
blur