Description

When working with nested objects or arrays, directly accessing deep properties like obj.a.b.c can cause errors if any level in the path doesn’t exist.


To handle this safely, developers use a helper function that traverses an object based on a string path (like "a.b.c") and returns the corresponding value if it exists — or undefined otherwise.


In this challenge, you’ll build your own Deep Object Getter function that safely accesses deeply nested values inside an object.


Your Task

Implement a function get(obj, keyStr) that:

  • Accepts an object obj and a string keyStr representing the property path (keys separated by dots .).
  • Traverses the object according to the keys.
  • Returns the value found at the end of the path.
  • Returns undefined if any part of the path is invalid or missing.
  • Supports array indices in the path (e.g., "a.b.0").

Method

Function

Description

get(obj, keyStr)

Safely retrieves the nested value from an object using a dot-separated string path.


Example

Input

const obj = {
a: {
b: {
c: [1, 2, 3],
},
},
};

console.log(get(obj, "a.b.c"));
console.log(get(obj, "a.b.c.0"));
console.log(get(obj, "a.b.c.e"));

Output

[1, 2, 3]
1
undefined

Expected Behavior

  • Returns the correct nested value if the full path exists
  • Returns undefined when a key is missing
  • Handles arrays correctly ("a.b.0")
  • Handles empty or invalid paths gracefully
  • Does not throw runtime errors

Hints


Hint 1

Use split('.') to break the path string into keys.

Hint 2

Use reduce() to traverse step by step.

Hint 3

Return undefined early if the current value is falsy (null/undefined).