We have an object (referenced by data
) and we want to retrieve the value of a nested property. Ideally, we would like to do it like so:
value = data.category3.section2.article4.title;
We cannot do this like so, because the above line throws a reference error if any of the mediate objects (category3
, section2
, or article4
) are not defined (at the corresponding positions) inside the data
object.
Now, to nullify any potential reference errors that might be thrown, we could just place the above line inside a try-catch
statement:
try {
value = data.category3.section2.article4.title;
} catch (err ) {}
This works! However, I am not confident that relying on try-catch
in such a way is a good practice. The alternative solution would be to manually traverse to the desired property value. I have written a compact utility function that accomplishes that:
function get( val, names ) {
names = names.split( '.' );
while ( val && names.length ) { val = val[ names.shift() ]; }
return val;
}
Now we can get the property value like so
value = get( data, 'category3.section2.article4.title' );
So, my question is:
Is the try-catch
approach a valid solution? Or are there valid reasons why it should be avoided?
Btw, the try-catch
approach is heavily biased in this thread: What's the simplest approach to check existence of deeply-nested object property in JavaScript?