Skip to content
Onsite

Lodash get

MediumP2Coding

Implement get(object, path, defaultValue), in the spirit of Lodash's _.get: read a nested value by path.

  • path is a string such as "a.b.c", "a[0].b" or "a[0][1]". Dots separate keys; [n] is an array index (or a key). path can also be an array of keys, such as ["a", "b", 0].
  • Return the value found at the path.
  • If any step along the path is missing, or passes through null or undefined, return defaultValue.
  • If the value found at the end is undefined, return defaultValue. Other falsy values (0, '', false, null) are real values and are returned as they are.
  • Never throw because of a missing step.

The path is non-empty and keys do not contain dots or brackets.

Example 1

Input
get({ a: [{ b: 5 }] }, 'a[0].b', 0) get({ a: 1 }, 'a.b.c', 'none')
Output
5 'none'

Constraints

  • Path length <= 100 keys

Hints

Run checks the 3 visible tests, Submit all 10.