Problem Statement
I need to access a deeply nested object. I could've used a 3rd party util such as Lodash but insisted myself on writing a Vanilla JS solution with a recursive strategy.
Code
Can this solution be improved with a better and more efficient approach? Is there any edge case which has been missed and could break the code?
const obj = {
foo: {
bar: {
baz: "value"
}
}
};
const getPathValue = (object, path) => {
if (
// ======= object checks ======= //
object === null ||
object === undefined ||
typeof object !== "object" ||
// ======= path checks ======= //
path === null ||
path === undefined ||
path.length === 0
) {
return undefined;
}
// key -> current key
// rest -> rest of the keys in path
const [key, ...rest] = path;
// value of current key
const value = object[key];
// if rest of the keys are exhausted &
// a value is found, return the value
if (rest.length === 0 && value) {
return value;
}
// as rest of key are not exhaused yet
// in the path, keep traversing deeper
return getPathValue(value, rest);
};
// ======= test cases with object edge cases ======= //
console.log(getPathValue()); // undefined
console.log(getPathValue(null)); // undefined
console.log(getPathValue(undefined)); // undefined
// ======= test cases with path edge cases ======= //
console.log(getPathValue(obj, [])); // undefined
console.log(getPathValue(obj, null)); // undefined
console.log(getPathValue(obj, [1, 2, 3])); // undefined
console.log(getPathValue(obj, ["non exisiting key"])); // undefined
console.log(getPathValue(obj, ["foo", "non exisiting key"])); // undefined
console.log(getPathValue(obj, ["foo", "bar", "baz", "non exisiting key"])); // undefined
console.log(getPathValue(obj, ["foo", "non exisiting key", "bar", "baz"])); // undefined
// ======= normal test case ======= //
console.log(getPathValue(obj, ["foo", "bar", "baz"])); // value