2

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?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
user2924127
  • 6,034
  • 16
  • 78
  • 136
  • 1
    Possible duplicate of [Accessing nested JavaScript objects with string key](http://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-with-string-key) – Evan Davis Jan 15 '16 at 19:53
  • 1
    I know that this is not strictly a dupe, but the solution to the oft-asked question I linked would fit your needs perfectly. – Evan Davis Jan 15 '16 at 19:54
  • 1
    If _lodash_ is okay you could use [`_.get()`](https://lodash.com/docs#get) `var value = _.get(data, "body.region.store.customer.name", undefined /*defaultValue*/)` – Andreas Jan 15 '16 at 19:55

2 Answers2

4
var myJson = null;
try {
    myJson = data.body.region.store.customer.name;
}
catch(err) {
    //display error message
}
Mat Forsberg
  • 454
  • 2
  • 10
1

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');
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59