Lodash get
MediumP2Coding
Implement get(object, path, defaultValue), in the spirit of Lodash's _.get: read a nested value by path.
pathis 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).pathcan 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
nullorundefined, returndefaultValue. - If the value found at the end is
undefined, returndefaultValue. 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
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 10. ⌘Enter runs, ⌘⇧Enter submits.