call(back)

Implement Lodash's get

Write get(obj, path, fallback): read a nested value by its path, and return fallback when the path leads nowhere.

get({ a: [{ b: { c: 3 } }] }, "a[0].b.c")             // 3
get({ a: [{ b: { c: 3 } }] }, ["a", "0", "b", "c"])  // 3
get({ a: {} }, "a.b.c", "none")                        // "none"

Rules

  • path is a string of dots and bracketed indices ("a[0].b" or "a.0.b"), or an array of keys. An array key is used as it is, even when it contains a dot.
  • Walking into null or undefined returns fallback, and so does a final value of undefined.
  • Every other value comes back as stored, including null, 0, false and "". The fallback is for missing values, not falsy ones.
  • Properties of primitives work too: "name.length".

Hints

Hint 1

Normalize the path first. An array is used as it is. A string becomes keys by turning each [n] into .n, splitting on dots, and dropping empty pieces.

Hint 2

Walk with cur = cur[key], checking cur == null before each step. After the loop, only undefined means missing.

Asked at