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)
- Normalize bracket notation
[0]into dot notation.0first. - Split the path by
.to get individual keys. - Walk through the object one key at a time.
- Return the default value if you encounter
nullorundefined.
Topics
- Objects
Asked at
Google · Amazon · Airbnb · Uber
