-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcode.js
More file actions
29 lines (22 loc) · 806 Bytes
/
code.js
File metadata and controls
29 lines (22 loc) · 806 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// safeGet: read nested path safely, return fallback if path not present
function safeGet(obj, path, fallback = null) {
return path.split('.').reduce((acc, key) => {
return acc?.[key];
}, obj) ?? fallback;
}
// Usage:
const user1 = {
id: 101,
name: "Garima",
address: { city: "Kolkata", pin: 700001 },
};
const user2 = {
id: 102,
name: "Geeta",
// address missing (maybe from incomplete API)
};
console.log(safeGet(user1, "address.city", "Unknown City")); // "Kolkata"
console.log(safeGet(user2, "address.city", "Unknown City")); // "Unknown City"
console.log(safeGet(user2, "preferences.theme", "light")); // "light"
// Alternative short using optional chaining directly. But safeGet is handy when path is dynamic (string).
const city = user2?.address?.city ?? "Unknown City";