0

I have an object nested within a property of a parent object. I need to find out if a property exist.

var o = {
 prop: {
       a: 'a',
       b: 'b' 
    }
}

Here are two approaches:

o.prop.hasOwnProperty('a'); // true

!!o.prop.a // true

What is the difference between the two? Any other alternatives?

GibboK
  • 71,848
  • 143
  • 435
  • 658
  • 1
    Please check out http://stackoverflow.com/questions/135448/how-do-i-check-if-an-object-has-a-property-in-javascript. It does not really matter that your object is nested. – g.kertesz Jan 23 '15 at 07:50
  • useful article: http://toddmotto.com/methods-to-determine-if-an-object-has-a-given-property/ – GibboK Jan 23 '15 at 07:59

1 Answers1

3

The difference is that the first example (hasOwnProperty) is ensuring that the property wasn't passed down the prototype chain, while the second would pass where 'a' was inherited from the prototype chain. You could also check using:

('a' in o.prop)
Rob M.
  • 35,491
  • 6
  • 51
  • 50
  • just a quick question, please.. I have a scenario where I need to check prop first before a.. what could be an concise way.. maybe ... ('prop' in o) && ('a' in o.prop) what do you suggest? thanks for your help – GibboK Jan 23 '15 at 07:56
  • 1
    As ugly as it is, yes, that is a typical approach for testing nested properties: `if(prop.o && prop.o.a){ ... }`. The `'attr' in object` syntax is nice, but I typically use it for dynamic attribute/function names. – Rob M. Jan 23 '15 at 08:03