Simple javascript / json question.
In my code I am finding a value for a variable from one of a number of sources (I try each in turn until I find one that is not undefined
). One of those sources is a json object with several levels of elements, not all of which are guaranteed to be populated.
Say, for example, the data that I need is found at options.levelA.levelB.levelC.dataThatINeed
. None of those levels is guaranteed to be set, including even the options variable itself.
To avoid runtime errors (trying to access a subelement of 'undefined'), is the only safe way to access dataThatINeed
to do so as follows:
var data = (options && options.levelA && options.levelA.levelB && options.levelA.levelB.levelC && options.levelA.levelB.levelC.dataThatINeed) || 'default';
It just seems like a very inelegant way to do it, with the real possibility of bugs (typos etc) slipping in with all of those levels to include. I wonder if there is a better practice to adopt. It's a shame you can't access options.levelA.levelB.levelC.dataThatINeed
directly, returning undefined
if dataThatINeed
(or any of the higher levels) is undefined
, rather than possibly throwing an error.
Thanks.