CodePark/ problems / Read a value by path
START PRACTICINGPRACTICE
Coding problem · JavaScript utilities › Recursion over nested objects

Read a value by path

mediumabout 20 minutes in an interview

Implement get(obj, path, defaultValue), in the style of lodash's get. It reads a value deep inside obj and returns it, or returns defaultValue when the value isn't there.

The path is either:

  • a string such as "user.posts[1].title". Dots separate keys. [1] is another way to write the key 1, so "user.tags.0" also works. Keys never contain dots or brackets themselves.
  • an array of keys such as ["user", "posts", 1, "title"].

Rules:

  • If any step reaches null or undefined before the path ends, return defaultValue. Never throw.
  • If the final value is undefined, return defaultValue. Any other value is returned, even 0, "", false or null.
  • Properties of primitives count: "user.name.length" on "Ada" gives 3.
  • An empty path ("" or []) returns defaultValue.
  • When defaultValue is left out, it is undefined.
Input: get({ a: { b: [{ c: 7 }] } }, 'a.b[0].c') Output: 7
Input: get({ a: null }, 'a.b.c', 'none') Output: 'none'
Input: get({ a: { n: null } }, 'a.n', 5) Output: nullonly undefined triggers the default