getProperty

Medium · Object Manipulation · 4 test cases

Safely retrieve a nested property from an object using a string path (e.g., 'a.b.c'). If any part of the path is undefined, return undefined.

Examples

getProperty({a: {b: {c: 1}}}, 'a.b.c') → 1
getProperty({a: {b: {c: 1}}}, 'a.b.d') → undefined
getProperty({a: 1}, 'a') → 1

Starter code

function getProperty(obj, path) {

}

Complexity of the optimal solution

Time O(k), space O(k). The function splits the path string into an array of keys and then uses `reduce` to traverse the object. The complexity is proportional to the number of keys 'k' in the path, not the size of the object itself.

Solve getProperty in the browser