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,
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:
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.
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) —
274 wordsLast Post: How to Check If Two Arrays are Similar in PHP?
Next Post: How to Flatten Javascript Arrays?