Middle+
/* Write a function get(obj, path), which takes an object obj and a string path representing the path to a value in the object. - If the path exists, the function should return the corresponding value - If the path does not exist, it should return undefined - The path is given as a string separated by dots(.) */ function get(obj, path) { } get({ a: { b: { c: "d" } } }, "a.b.c"); get({ a: { b: { c: "d" } } }, "a.b"); get({ x: { y: { z: 42 } } }, "x.c");
sobes.tech AI
Answer from AI
The get function splits the path string by dots and sequentially traverses the object, returning the value at the specified path or undefined if the path does not exist.
function get(obj, path) {
return path.split('.').reduce((acc, key) => {
if (acc && acc.hasOwnProperty(key)) {
return acc[key];
} else {
return undefined;
}
}, obj);
}
// Examples:
console.log(get({ a: { b: { c: "d" } } }, "a.b.c")); // "d"
console.log(get({ a: { b: { c: "d" } } }, "a.b")); // { c: "d" }
console.log(get({ x: { y: { z: 42 } } }, "x.c")); // undefined