I need a function that takes as its first parameter an object, and as its second parameter a string to pass through to get the value. If any of the properties is not found, the function returns undefined.
I can do it with reduce. but how can I do it with recursion? will it be faster with recursion?
const obj = {a: {b: {c: {d: 'Hello'}}}}
function optionalChaining (obj, path) {
// recursion solution
}
expected result:
optionalChaining(obj, "a.b.c"); // { d: 'Hello' }
optionalChaining(obj, "a.b.c.d"); // Hello
optionalChaining(obj, "a.b.c.d.e"); // undefined
optionalChaining(obj, "b.d.a"); // undefined