We always use an object to read and write data in javascript.
Suppose this object
const obj = {
one:{
two:{
three:{
four:{
data:"This is the data"
}
}
}
}
}
Any attribute at any level of nesting can be null or undefined.
For example
obj = null;
obj.one = null;
obj.one.two = undefined;
So, if we are concerned with property data from the object obj.
We will use it like this.
const data = obj?obj.one?obj.one.two?obj.one.two:"":"":""; // so on...
What I tried is
let data = "";
try{
data = obj.one.two.three.four.data;
}catch(e){}
This way at any stage if we try to encounter an operation like, one is undefined and we are trying to read the property of one. Then, in this case, it'll throw an error and data will be an empty string.
It works fine
As I don't have much experience, so I would like to know from the community that, is a good way of reading the data?
Top comments (0)