Access Javascript Nested objects or Attributes safely
It is very likely to get run time exceptions on trying to read value of undefined or null objects in Javascript.
There are two ways we can solve this common development issue.
The optional chaining operator, also known as the safe navigation operator, is a feature of ECMAScript 2020 and Node v14 that would enable you to write your example as follows:
var a = b?.c?.d;
If your node and the javascript version is older than the above specification, then we can go ahead and implement our own safe function to retrive nested object values.
As the first step, let’s define a function that takes two params, one which is a function param, this can be our object access, and anotehr param for default value.
As you can observe, if at any point the function failes, it will return the default value, without crashing the whole app.
static getSafe(fn, defaultVal) {
try {
if(fn()){
return fn();
}
return defaultVal;
} catch (e) {
return defaultVal;
}
}
We can use the above function as follows to access nested objects:
let user={
name:"sam",
application:{
number:"N123"
}
};
console.log(getSafe(()=>user.name,""));//access first level and if not found log empty string
console.log(getSafe(()=>user.application.number,""));//access second level and if not found log empty string