I'd probably do it with JavaScript's curiously-powerful &&
operator (the cousin of the curiously-powerful ||
operator you're already using):
var topLevel = testdata['key'];
var nextLevel = topLevel && topLevel['subkey'];
// ...
If topLevel
is falsey (null
, undefined
, and so on), nextLevel
will get that falsey value (the left-hand operand); if not, the right-hand operand is evaluated and nextLevel
receives the value of that. Using these kinds of guards, you can keep going as long as you want.
var topLevel = testdata['key'];
var nextLevel = topLevel && topLevel['subkey'];
var nextNextLevel = nextLevel && nextLevel['key3'];
var nextNextNextLevel = nextNextLevel && nextNextLevel['key4'];
This is really handy when you're expecting an object reference, null
, or undefined
.