Lets say I parse a JSON object from a 3rd party source:
var myObject = {
  person_list: [
    { black_hair: {
      list: [
        'bob',
        'john',
        'allen'
      ]}
    }
  ]
};
But if the structure suddenly changes or perhaps the data response was corrupt, how can I check the existence of the in depth parts of the structure?
I can do
if ( myObject.person_list.black_hair.list !== undefined ) {
  // do stuff
}
But maybe black_hair doesn't exist in some cases. If it's missing from the object, then I get a Uncaught TypeError: Cannot read property 'list' of undefined. So the only way I can think of to check if the entire structure is complete is to check if each level is defined:
if ( myObject.person_list !== undefined ) {
  if ( myObject.person_list.black_hair !== undefined ) {
    if ( myObject.person_list.black_hair.list !== undefined ) {
      // do stuff
    }
  }
}
But that is a little bit ridiculous. Is there a simple way to handle this in JavaScript? Is a try, catch the best approach?
You could define a function to check the full structure for you:
function defined_structure(obj, attrs) {
    var tmp = obj;
    for(i=0; i<attrs.length; ++i) {
        if(tmp[attrs[i]] == undefined)
            return false;
        tmp = tmp[attrs[i]];
    }
    return true;
}
//...
if(defined_structure(myObject, ['person_list', 0, 'black_hair', 'list']) {
    // Do stuff
}
The first parameter is the object with structure to be checked, and the second one is an array with the name of the nested properties.
Update:
As pointed out by @chiliNUT, person_list is an array. Anyway, this approach works by adding the index of the item you want to check (i.e. ['person_list', 0, 'black_hair', 'list']).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With