Test for existence of nested JavaScript object key

If I have a reference to an object:

var test = {};

that will potentially (but not immediately) have nested objects, something like:

{level1: {level2: {level3: "level3"}}};

What is the best way to test for the existence of keys in the most deeply nested objects?

alert(test.level1); yields undefined , but alert(test.level1.level2.level3); fails.

I'm currently doing something like this:

if(test.level1 && test.level1.level2 && test.level1.level2.level3) {
    alert(test.level1.level2.level3);
}

but I was wondering if there's a better way.


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

Here is a pattern I picked up from Oliver Steele:

var level3 = (((test || {}).level1 || {}).level2 || {}).level3;
alert( level3 );

In fact that whole article is a discussion of how you can do this in javascript. He settles on using the above syntax (which isn't that hard to read once you get used to it) as an idiom.


Update

Looks like lodash has added _.get for all your nested property getting needs.

_.get(countries, 'greece.sparta.playwright')

https://lodash.com/docs#get


Previous answer

lodash users may enjoy lodash.contrib which has a couple methods that mitigate this problem.

getPath

Signature: _.getPath(obj:Object, ks:String|Array)

Gets the value at any depth in a nested object based on the path described by the keys given. Keys may be given as an array or as a dot-separated string. Returns undefined if the path cannot be reached.

var countries = {
        greece: {
            athens: {
                playwright:  "Sophocles"
            }
        }
    }
};

_.getPath(countries, "greece.athens.playwright");
// => "Sophocles"

_.getPath(countries, "greece.sparta.playwright");
// => undefined

_.getPath(countries, ["greece", "athens", "playwright"]);
// => "Sophocles"

_.getPath(countries, ["greece", "sparta", "playwright"]);
// => undefined
链接地址: http://www.djcxy.com/p/70102.html

上一篇: 为什么数组中的var返回一个字符串索引?

下一篇: 测试嵌套JavaScript对象键的存在性