Problem 44
Object Path Lookup Recursion Challenge
Given an object and an array of keys representing a path, return the value found by following the keys through the object. If the path cannot be followed at any point, return undefined.
Function Signature
getByPath(object, path)
Parameters
object— an object or value to traverse.path— an array of keys (strings or numbers) representing the lookup path.
Output
Return the value at the given path, or undefined if the path is invalid.
Constraints
- The function must use recursion.
- The input object and path must not be mutated.
- The function should accept exactly two arguments.
Examples
getByPath({user: {profile: {name: 'Ada'}}}, ['user', 'profile', 'name']) → 'Ada'
getByPath({active: true}, ['active']) → true
getByPath({users: [{name: 'Ada'}]}, ['users', 0, 'name']) → 'Ada'
getByPath({a: {b: 1}}, ['a', 'c']) → undefined
getByPath({a: 1}, []) → {a: 1}
Edge Cases
- An empty path returns the input object itself.
- If the object at any point in the path is
nullorundefined, returnundefined.