Back to Objects & JSONMedium
Exercise 9: Get Nested Property Value
Problem Statement
Function `get(obj, path, defaultValue)` banao jo nested object se property value get kare using path string.
Example: get({a: {b: {c: 1}}}, "a.b.c") => 1
Sample Output:
get({a: {b: {c: 1}}}, "a.b.c") => 1
get({a: {b: 1}}, "a.b.c", "default") => "default"Solution
const get = (obj, path, defaultValue) => {
const keys = String(path).split(".");
let current = obj;
for (const key of keys) {
if (current == null || typeof current !== "object") return defaultValue;
current = current[key];
}
return current !== undefined ? current : defaultValue;
};Explanation
Overall Goal:
- Nested object se path string se value get karna.
Real world:
- Data access: safe nested access.
- API responses: nested data access.