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 key1, 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
nullorundefinedbefore the path ends, returndefaultValue. Never throw. - If the final value is
undefined, returndefaultValue. Any other value is returned, even0,"",falseornull. - Properties of primitives count:
"user.name.length"on"Ada"gives3. - An empty path (
""or[]) returnsdefaultValue. - When
defaultValueis left out, it isundefined.
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