In Javascript, given object var x = {a: {b: {c: “value”} } }, we can retrieve/access the field by x.a.b.c However, if a field doesn’t exist, exception will be thrown and the code will stop running.
Let’s implement a safeGet function that allows you to easily retrieve the field and return undefined if a field doesn’t exist. For example,
1 2 3 4 5 | var data = { a: { b: { c: 'HelloACM' } } } safeGet(data, 'a.b.c') // => HelloACM safeGet(data, 'a.b.c.d') // => undefined safeGet(data, 'a.b.c.d.e.f.g') // => undefined console.log("hello"); // "hello" will be printed |
var data = { a: { b: { c: 'HelloACM' } } } safeGet(data, 'a.b.c') // => HelloACM safeGet(data, 'a.b.c.d') // => undefined safeGet(data, 'a.b.c.d.e.f.g') // => undefined console.log("hello"); // "hello" will be printed
The Javascript implementation of safeGet is simple: split the path string and iterate the array and navigate the pointer to the fields. Iterating the array can be done via forEach:
1 2 3 4 5 6 7 8 9 10 11 12 13 | const safeGet = (data, path) => { if (!path) return undefined; let found = true; path.split(".").forEach(function(v) { if (data[v]) { data = data[v]; } else { found = false; return; } }); return found ? data : undefined; } |
const safeGet = (data, path) => { if (!path) return undefined; let found = true; path.split(".").forEach(function(v) { if (data[v]) { data = data[v]; } else { found = false; return; } }); return found ? data : undefined; }
We can do a while loop and using .shift() method to pop up the first element in the array one by one.
1 2 3 4 5 6 7 8 9 10 | const safeGet = (data, path) => { if (!path) return undefined; let paths = path.split('.'); let res = data; while (paths.length) { res = res[paths.shift()] if (!res) return undefined; } return res; } |
const safeGet = (data, path) => { if (!path) return undefined; let paths = path.split('.'); let res = data; while (paths.length) { res = res[paths.shift()] if (!res) return undefined; } return res; }
–EOF (The Ultimate Computing & Technology Blog) —
GD Star Rating
loading...
291 wordsloading...
Last Post: How to Check If Two Arrays are Similar in PHP?
Next Post: How to Flatten Javascript Arrays?