-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwriteSafeGet.js
More file actions
32 lines (27 loc) · 719 Bytes
/
writeSafeGet.js
File metadata and controls
32 lines (27 loc) · 719 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
30
31
32
function safeGet(obj, selectors, defaultValue) {
if (typeof selectors === "string") {
selectors = selectors.split(".");
}
const selector = selectors.reduce((acc, value) => {
return acc[value];
}, obj);
if (typeof selector !== "undefined") {
return selector;
}
return defaultValue;
}
let obj = {
location: {
state: {
city: false
}
},
hello: {
firstName: "Monica"
}
};
console.log(safeGet(obj, ["location", "state", "city"])); //false
console.log(safeGet(obj, "location.state.city")); //false
console.log(safeGet(obj, "name.firstName")); //"Monica"
console.log(safeGet(obj, "name.world", "World")); // "World"
console.log(safeGet(obj, "name.world")); // undefined