0

Does anyone know a clean way to find out if an object property exists? Here is my example:

var test = {
  a : 'west',
  b : {
    a : 'rest'
  },
  d : {
    a : 'pest'
  }
};
// I want to access 'a' in 'c'
typeof test.c.a; // fails!

typeof it seems can't get past the fact that 'c' doesn't exist to check if 'a' exists inside it (I've also tried jQuery.type() which also fails in the same way - I would have thought it would have error checking inside that function).

In this example of course I could simply check if 'c' exists first but in my real situation I have a large and deep object and I need to dynamically retrieve data from any potential location so it would be nice if there were a ready-made solution which didn't necessitate having to use a try-catch.

Thanks in advance!

RobG
  • 142,382
  • 31
  • 172
  • 209
dVyper
  • 187
  • 10
  • @raghavendra Exception handling should be for... exceptions. If you can check for something beforehand, you really ought to. – James Thorpe Aug 12 '15 at 11:54
  • @JamesThorpe there is no other way better than this. i suggest use it if your require to check property exists not in very depth level. – Raghavendra Aug 12 '15 at 11:55
  • @raghavendra Check the duplicate. You most certainly can check without an error being thrown. In some circumstances, throwing and catching an exception can be a lot slower than just checking it in advance. – James Thorpe Aug 12 '15 at 11:59
  • With lodash: [`_.has(test, "c.a")`](https://lodash.com/docs#has) or [`_.get(test, "c.a")`](https://lodash.com/docs#get) – Andreas Aug 12 '15 at 12:00
  • @JamesThorpe op menetion he has to check existence of a property in depths so it better way to do go like this. – Raghavendra Aug 12 '15 at 12:01
  • @JamesThorpe yes you are correct sorry. I found an answer in that question thanks – dVyper Aug 12 '15 at 12:02

1 Answers1

0

I can't vouch for any existing functionality in any js framework for finding nested properties, but you can certainly roll your own.

hasOwnProperty is part of the ECMA script standard.

if(test.hasOwnProperty("c"))
{
   console.log("test.c = " + test.c);
}

If you are looking to find deeply nested properties, then you could roll your own function to check if the nested property exists, and if so, return it.

function hasNestedProperty(testObject, properties)
{
  var maxDepth = properties.length;
  var i, hasProperty = false;
  var currObj = testObject;
  
  while(hasProperty && i < maxDepth)
  {
      if(currObj.hasOwnProperty(properties[i])
      {
         currObj = currObj[properties[i]]);
         i ++;
      }
      else
      {
         hasProperty = false;
      }
  }
                                  
  return hasProperty;
}
Robominister
  • 146
  • 5