javascript test for existence of nested object key -
if have reference object -
var test = {};
that potentially (but not immediately) have nested objects, -
{ level1:{level2:{level3:'level3'}} };
what best way test existence of keys in nested objects?
this -
alert(test.level1);
returns 'undefined', -
alert(test.level1.level2.level3);
fails.
i'm doing -
if(test.level1 && test.level1.level2 && test.level1.level2.level3) { alert(test.level1.level2.level3); }
but wondering if there's better way.
you have step step if don't want typeerror
, because if 1 of members null
or undefined
, , try access member exception thrown.
you can either catch
exception, or make function test existence of multiple levels, this:
function checknested(obj /*, level1, level2, ... leveln*/) { var args = array.prototype.slice.call(arguments, 1); (var = 0; < args.length; i++) { if (!obj || !obj.hasownproperty(args[i])) { return false; } obj = obj[args[i]]; } return true; } var test = {level1:{level2:{level3:'level3'}} }; checknested(test, 'level1', 'level2', 'level3'); // true checknested(test, 'level1', 'level2', 'foo'); // false
Comments
Post a Comment