92

And of course I want to do this code-wise. It's not that there isn't alternative to this problem I'm facing, just curious.

Andrew Eisenberg
  • 27,549
  • 9
  • 90
  • 141
Khoi
  • 4,324
  • 5
  • 27
  • 31

4 Answers4

148

This will ignore attributes passed down through the prototype chain.

if(obj.hasOwnProperty('field'))
{
    // Do something
}
Gary Chambers
  • 23,604
  • 4
  • 32
  • 29
94

UPDATE: use the hasOwnProperty method as Gary Chambers suggests. The solution below will work, but it's considered best practice to use hasOwnProperty.

if ('field' in obj) {
}
Peter Kruithof
  • 9,874
  • 5
  • 28
  • 42
  • 1
    Note that exactly the same way you can check the existence of a key in an associative array (this is because usually objects **are** in fact associative arrays) – Andrea Zilio Aug 13 '10 at 11:21
  • Some linters will complain about this syntax. It is safer to use hasOwnProperty as suggested by @GaryChambers – Jayd Jun 02 '14 at 14:11
  • Agreed, I updated my answer to point other people to the right direction. – Peter Kruithof Jun 02 '14 at 15:23
  • @Jayd What are the downsides of this syntax compared to hasOwnProperty? – Jo Smo Dec 11 '15 at 17:18
  • 3
    @JoSmo the in syntax could return true for attributes up the prototype chain as Gary Chambers mentioned in his answer. Has own property will only check for fields that endemic to the current object. – Jayd Jan 07 '16 at 08:56
  • For example, if obj is a Mongoose (v4.13.7) model instance and 'field' is not in the object but 'field' is in the model's schema, then ('field' in obj) === true but (typeof obj.field) === 'undefined' and obj.hasOwnProperty('field') === false. – Steve Mitchell Jan 02 '18 at 11:13
8

In addition to the above, you can use following way:

if(obj.myProperty !== undefined) {
}
Eugene Ilyushin
  • 576
  • 7
  • 13
  • 7
    This method cannot distinguish between missing field and existing field with undefined value. For example: `{}` and `{a : undefined}` – Arashsoft Apr 11 '18 at 16:47
  • @Arashsoft have you found a use case where those two situations cause a substantial difference? For example, a test failing, or something in the UI not being rendered correctly? – Jason Oct 01 '21 at 22:11
  • @Jason That is not the point. The point is you can't check for the presence of a field in an object with this. – Paschal Dec 25 '21 at 04:55
0

There is has method in lodash library for this. It can even check for nested fields.

_.has(object, 'a');     
_.has(object, 'a.b');
Aliaksandr Sushkevich
  • 9,760
  • 6
  • 35
  • 41