Skip to content
SDETRole
SDETRole

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].id and grid[1][0].
  • Return defaultValue (which may be omitted, giving undefined) when any step along the path is missing or is null/undefined.
  • Return the real value when it exists, even if it is 0, false or ''.
  • 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.

Type to search across SDETRole.

Full-text search by Pagefind · runs in your browser Open search page →