coding round · ~15 min
JavaScriptintermediate

Implement get(obj, path)

Write get(obj, path, defaultValue) that safely reads a nested value. path is either a string with dots and bracket indexes, like 'a.b[0].c', or an array of keys, like ['a', 'b', '0', 'c'].

  • get({ a: { b: [{ c: 1 }] } }, 'a.b[0].c') → 1
  • get({ a: { b: [{ c: 1 }] } }, ['a', 'b', '0', 'c']) → 1
  • get({ a: null }, 'a.b.c', 'none') → 'none'
  • get({ a: { b: 0 } }, 'a.b', 5) → 0

If a step along the way is null or undefined, or the final value is undefined, return defaultValue (which is undefined when it's omitted). Other falsy values, such as 0, false, '' and a final null, are real values and are returned as they are.

Define get in the editor. 7 tests will call it.

solution.js
function get(obj, path, defaultValue) {
  // path is a string like 'a.b[0].c' or an array like ['a', 'b', '0', 'c'].
  // Return defaultValue when the value can't be reached or is undefined.
}

Tests⌘/Ctrl + Enter to run

reads nested properties with a dot path
supports bracket indexes
supports array paths
returns the default when the path does not exist
stops safely at null and undefined along the way
returns falsy values instead of the default
can read properties of primitives
esc