0

Let's say we have a window object that looks like window.someObject.someProperty.subProperty and we have an if condition where we check if subProperty === "foo".

In order to avoid a cannot read property xxx of undefined I would have to write something like

if (window.someObject && window.someObject.someProperty &&  window.someObject.someProperty.subProperty === "foo") {
      // do something
}

Now imagine the object has more properties, it would be very long to check for all of them.

So my question is whether or not there is a faster way to perform that check without having to write all the sequence of properties.

callback
  • 3,981
  • 1
  • 31
  • 55

2 Answers2

0

Usually when working with an API you should be able to anticipate what could be missing and what shouldn't. Sadly there's no shorter way to check if you want to be sure on each step. However there are preprocessors such as CoffeeScript which allow you to do this: window.someObject?.someProperty?.subProperty

But no vanilla way.

GMchris
  • 5,439
  • 4
  • 22
  • 40
0

Already answered in javascript test for existence of nested object key Please check their generic function

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
Community
  • 1
  • 1
  • [Please don't copy and paste answers, instead reference them.](http://stackoverflow.com/a/2631198/1293700) – Darius May 16 '16 at 11:08