Get a value by path
intermediate Recursion Challenge 8 of 18
Write getByPath(obj, path, defaultValue), which reads a value from nested objects and arrays using a path string. API assertion helpers often take paths like this from a data table.
Requirements
- Support dot segments and numeric array indexes, for example
data.items[0].idandgrid[1][0]. - Return
defaultValue(which may be omitted, givingundefined) when any step along the path is missing or isnull/undefined. - Return the real value when it exists, even if it is
0,falseor''. - Never throw for a missing path.
Expected output
getByPath({ a: { b: [{ c: 5 }] } }, 'a.b[0].c') → 5 getByPath({ a: null }, 'a.b.c', 'n/a') → 'n/a'
Test cases (7)
- ○reads nested objects and arrays
- ○returns the default for a missing key
- ○returns the default when an intermediate value is null
- ○returns undefined when no default is given
- ○returns falsy values instead of the default
- ○supports nested array indexes
- ○an out-of-range index returns the default
solution.jsExecutes in your browser
Ctrl/⌘ + Enter to run tests · your code is saved in this browser
Results
Run the tests to see results here.