Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Your current solution is probably as good as you can get, as mVChr says, try..catch is just lazy here. It's probably far less effient and has nothing to recommend it other than perhaps being easier to type (but not significantly so) and it'll be harder to debug as it silently hides errors.</p> <p>The real issue is the very long "reference worm" created by attempting such access. An alternative to the original that at least reduces the number of property lookups is:</p> <pre><code>var o; if ( (o = entry ) &amp;&amp; (o = o.mediaGroup) &amp;&amp; (o = o[0] ) &amp;&amp; (o = o.contents ) &amp;&amp; (o = o[0] )) { alert(o.url); } </code></pre> <p>But I expect you won't like that.</p> <p>If you have many such deep access paths, you might like to create a function to do the access and return the last object on success or some other vaule on failure. For failure, you could also have it return the last non-falsey object on the path.</p> <pre><code>// Create test object var entry = {}; entry.mediaGroup = [{ contents: [{url: 'url'}] }]; // Check that it "works" // alert(entry.mediaGroup[0].contents[0].url); // Deep property access function, returns last object // or false function deepAccess(obj) { var path = arguments; var i = 0, iLen = path.length; var o = path[i++]; // o is first arg var p = path[i++]; // p is second arg // Go along path until o[p] is falsey while (o[p]) { o = o[p]; p = path[i++]; } // Return false if didn't get all the way along // the path or the last non-falsey value referenced return (--i == iLen) &amp;&amp; o; } // Test it var x = deepAccess(entry, 'mediaGroup','0','contents','0'); alert(x &amp;&amp; x.url); // url var x = deepAccess(entry, 'mediaGroup','1','contents','0'); alert(x &amp;&amp; x.url); // false </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload