Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if object structure exists?

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?

like image 775
Jake Wilson Avatar asked Jul 24 '14 03:07

Jake Wilson


1 Answers

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']).

like image 71
Sergio A. Avatar answered Sep 20 '22 18:09

Sergio A.