user2924127
user2924127

Reputation: 6252

Check if nested object is declared and has a value without so many conditional checks

I have a JSON object which I get from a server. The key which I get the value from looks something like this:

var myJson = data.body.region.store.customer.name;

I am trying to get the name key here, but sometimes the JSON (which comes from a service I have no control over) will have some empty fields, like for instance name might not be defined so the object will actually look like this: data.body.region.store.customer. Sometimes too customer, or store, or region might not be defined (If the data doesn't exist the service doesn't return a null or empty string for the value).

So if I need the name what I am doing is this:

if(data.body.region.store.customer.name){
   //Do something with the name
}

But say even store isn't defined, it will not get the value for name(which I would expect to be undefined since it doesn't exist) and the program crashes. So what I am doing now is checking every part of the JSON before I get the value with AND operands:

if(data && data.body && data.body.region && data.body.region.store && data.body.region.store.customer && data.body.region.store.customer.name){
     //Do something with the name value then
}

This works, because it checks sequentially, so it first checks does data exist and if it does it checks next if data.body exists and so on. This is a lot of conditions to check every time, especially since I use the service a lot for many other things and they need their own conditions too. So to just check if the name exists I need to execute 6 conditions which of course doesn't seem very good performance wise (and overall coding wise). I was wondering if there is a simpler way to do this?

Upvotes: 2

Views: 124

Answers (2)

Mat Forsberg
Mat Forsberg

Reputation: 454

var myJson = null;
try {
    myJson = data.body.region.store.customer.name;
}
catch(err) {
    //display error message
}

Upvotes: 4

Nikhil Aggarwal
Nikhil Aggarwal

Reputation: 28475

You can try following

function test(obj, prop) {
    var parts = prop.split('.');
    for(var i = 0, l = parts.length; i < l; i++) {
        var part = parts[i];
        if(obj !== null && typeof obj === "object" && part in obj) {
            obj = obj[part];
        }
        else {
            return false;
        }
    }
    return true;
}

test(myJson, 'data.body.region.store.customer.name');

Upvotes: 1

Related Questions