Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

test the existence of property in a deep object structure

Tags:

javascript

In javascript, lets say I want to access a property deep in an object, for example:

entry.mediaGroup[0].contents[0].url

At any point along that structure, a property may be undefined (so mediaGroup may not be set).

What is a simple way to say:

if( entry.mediaGroup[0].contents[0].url ){
   console.log( entry.mediaGroup[0].contents[0].url )
}

without generating an error? This way will generate an undefined error if any point along the way is undefined.

My solution

if(entry) && (entry.mediaGroup) && (entry.MediaGroup[0]) ...snip...){
   console.log(entry.mediaGroup[0].contents[0].url)
}

which is pretty lengthy. I am guessing there must be something more elegant.

like image 475
RobKohr Avatar asked Jun 01 '11 22:06

RobKohr


1 Answers

This is a very lazy way to do it, but it meets the criteria for many similar situations:

try {
  console.log(entry.mediaGroup[0].contents[0].url);
} catch (e) {}

This should not be done on long code blocks where other errors may potentially be ignored, but should be suitable for a simple situation like this.

like image 105
mVChr Avatar answered Oct 29 '22 01:10

mVChr