Suppose I parse a JSON object from a third-party source:
var myObject = { person_list: [ { black_hair: { list: [ 'bob', 'john', 'allen' ]} } ] };
But if the structure suddenly changes or perhaps the data corruption was damaged, how can I check for the presence of the deepest parts of the structure?
I can do
if ( myObject.person_list.black_hair.list !== undefined ) { // do stuff }
But perhaps black_hair does not exist in some cases. If it is not in the object, I get Uncaught TypeError: Cannot read property 'list' of undefined . So the only way I can check if the whole 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 this is a little ridiculous. Is there an easy way to handle this in JavaScript? Try it, get the best approach?
source share