You have to do it step by step if you don't want a TypeError
, because if one of the members is null
or undefined
, and you try to access a member an exception will be thrown.
You can either simply catch
the exception, or make a function to test the existence of multiple levels, something like this:
function checkNested(obj /*, level1, level2, ... levelN*/) {
var args = Array.prototype.slice.call(arguments, 1);
for (var i = 0; i < 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
manpreet
Best Answer
2 years ago
If I have a reference to an s://forum.tuteehub.com/tag/object">object:
that will potentially (but not is://forum.tuteehub.com/tag/m">ms://forum.tuteehub.com/tag/m">mediately) have nested s://forum.tuteehub.com/tag/s://forum.tuteehub.com/tag/object">objects">s://forum.tuteehub.com/tag/object">objects, sos://forum.tuteehub.com/tag/m">mething like:
What is the s://forum.tuteehub.com/tag/best">best way to test for the existence of keys in the s://forum.tuteehub.com/tag/m">most deeply nested s://forum.tuteehub.com/tag/s://forum.tuteehub.com/tag/object">objects">s://forum.tuteehub.com/tag/object">objects?
alert(test.level1);
yieldsundefined
, butalert(test.level1.level2.level3);
fails.I’s://forum.tuteehub.com/tag/m">m currently doing sos://forum.tuteehub.com/tag/m">mething like this:
but I was wondering if there’s a better way.