admin管理员组

文章数量:1125973

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 check for the existence of property in 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.

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 check for the existence of property in 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.

Share Improve this question edited Jun 23, 2019 at 12:41 Bergi 663k158 gold badges1k silver badges1.5k bronze badges asked Apr 13, 2010 at 15:47 user113716user113716 322k64 gold badges453 silver badges441 bronze badges 9
  • 1 you might want to check a tangentially related question that was asked recently stackoverflow.com/questions/2525943/… – Anurag Commented Apr 13, 2010 at 16:21
  • See also stackoverflow.com/questions/10918488/… – James McMahon Commented Dec 21, 2012 at 15:38
  • A couple of propositions there : stackoverflow.com/a/18381564/1636522 – user1636522 Commented Sep 7, 2013 at 7:27
  • Your current approach has a potential issue if level3 property is a false, in that case, even if the property exist will retur nfalse have a look at this example please jsfiddle.net/maz9bLjx – GibboK Commented Jul 11, 2015 at 6:18
  • 13 simply you can use try catch also – Raghavendra Commented Aug 12, 2015 at 12:07
 |  Show 4 more comments

64 Answers 64

Reset to default 1 2 3 Next 734 +500

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

ES6 UPDATE:

Here is a shorter version of the original function, using ES6 features and recursion (it's also in proper tail call form):

function checkNested(obj, level,  ...rest) {
  if (obj === undefined) return false
  if (rest.length == 0 && obj.hasOwnProperty(level)) return true
  return checkNested(obj[level], ...rest)
}

However, if you want to get the value of a nested property and not only check its existence, here is a simple one-line function:

function getNested(obj, ...args) {
  return args.reduce((obj, level) => obj && obj[level], obj)
}

const test = { level1:{ level2:{ level3:'level3'} } };
console.log(getNested(test, 'level1', 'level2', 'level3')); // 'level3'
console.log(getNested(test, 'level1', 'level2', 'level3', 'length')); // 6
console.log(getNested(test, 'level1', 'level2', 'foo')); // undefined
console.log(getNested(test, 'a', 'b')); // undefined

The above function allows you to get the value of nested properties, otherwise will return undefined.

UPDATE 2019-10-17:

The optional chaining proposal reached Stage 3 on the ECMAScript committee process, this will allow you to safely access deeply nested properties, by using the token ?., the new optional chaining operator:

const value = obj?.level1?.level2?.level3 

If any of the levels accessed is null or undefined the expression will resolve to undefined by itself.

The proposal also allows you to handle method calls safely:

obj?.level1?.method();

The above expression will produce undefined if obj, obj.level1, or obj.level1.method are null or undefined, otherwise it will call the function.

You can start playing with this feature with Babel using the optional chaining plugin.

Since Babel 7.8.0, ES2020 is supported by default

Check this example on the Babel REPL.

本文标签: