DEV Community

Rahul kumar
Rahul kumar

Posted on

What is the best way to read an attribute from a long object chain?

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"
                }
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Any attribute at any level of nesting can be null or undefined.

For example

obj = null;
obj.one = null;
obj.one.two = undefined;
Enter fullscreen mode Exit fullscreen mode

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...
Enter fullscreen mode Exit fullscreen mode

What I tried is

let data = "";
try{
data = obj.one.two.three.four.data;
}catch(e){}
Enter fullscreen mode Exit fullscreen mode

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)