Implement get(obj, path)
Write get(obj, path, defaultValue) that safely reads a nested value. path is either a string with dots and bracket indexes, like 'a.b[0].c', or an array of keys, like ['a', 'b', '0', 'c'].
get({ a: { b: [{ c: 1 }] } }, 'a.b[0].c')→1get({ a: { b: [{ c: 1 }] } }, ['a', 'b', '0', 'c'])→1get({ a: null }, 'a.b.c', 'none')→'none'get({ a: { b: 0 } }, 'a.b', 5)→0
If a step along the way is null or undefined, or the final value is undefined, return defaultValue (which is undefined when it's omitted). Other falsy values, such as 0, false, '' and a final null, are real values and are returned as they are.
Define get in the editor. 7 tests will call it.
Hint 1Start by turning the path into an array of keys. For a string, replace each '[' with '.', remove each ']', split on '.' and filter out empty pieces.
Hint 2Walk the keys one at a time, and return the default as soon as the current value is null or undefined, before reading the next key.
Hint 3At the end, only fall back to the default if the value is undefined, so 0, false, '' and null are returned as they are.
one clean solution
function get(obj, path, defaultValue) {
const keys = Array.isArray(path)
? path
: String(path)
.replaceAll('[', '.')
.replaceAll(']', '')
.split('.')
.filter(Boolean);
let current = obj;
for (const key of keys) {
if (current === null || current === undefined) return defaultValue;
current = current[key];
}
return current === undefined ? defaultValue : current;
}