-
-
Save jeneg/9767afdcca45601ea44930ea03e0febf to your computer and use it in GitHub Desktop.
| function get(obj, path, def) { | |
| var fullPath = path | |
| .replace(/\[/g, '.') | |
| .replace(/]/g, '') | |
| .split('.') | |
| .filter(Boolean); | |
| return fullPath.every(everyFunc) ? obj : def; | |
| function everyFunc(step) { | |
| return !(step && (obj = obj[step]) === undefined); | |
| } | |
| } |
I would just use optional chaining and nullish coalescing:
https://caniuse.com/?search=optional%20chaining
https://caniuse.com/?search=nullish%20coalescing
Its pretty well supported now.
@SupremeTechnopriest, out of interest, how would you go about using that in situations where you don't know what the path is going to be? e.g. you have an object and a counterpart configuration that targets different portions of it.
If you knew the depth you could do something like:
const obj = {
a: {
b: {
c: 1
}
}
}
const path = 'a.b.c'
const fallback = 2
const parts = path.split('.')
const value = obj[parts[0]]?.[parts[1]]?.[parts[2]] ?? fallback
console.log(value) // 1If you don't know the depth, I think the get method is going to be the best route. You could check the length of parts and do a switch and handle all possible depths, but Im not sure if thats going to out perform the get methods above.
Maybe I will maintain a benchmark for this problem.
Not the fastest one but working for me:
Checked with the next tests: