Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine whether an object has a given property in JavaScript

People also ask

How do you check if an object has a specific property in JavaScript?

We can check if a property exists in the object by checking if property !== undefined . In this example, it would return true because the name property does exist in the developer object.

How do you know if an object has no property?

keys() method to check if there are any properties defined in an object. It returns an array of object's own keys (or property names). We can use that array to check if it's length is equal to 0 . If it is, then it means the object has no properties.

How do you check if a property exists in an object TypeScript?

To check if a property exists in an object in TypeScript: Mark the specific property as optional in the object's type. Use a type guard to check if the property exists in the object. If accessing the property in the object does not return a value of undefined , it exists in the object.


Object has property:

If you are testing for properties that are on the object itself (not a part of its prototype chain) you can use .hasOwnProperty():

if (x.hasOwnProperty('y')) { 
  // ......
}

Object or its prototype has a property:

You can use the in operator to test for properties that are inherited as well.

if ('y' in x) {
  // ......
}

If you want to know if the object physically contains the property @gnarf's answer using hasOwnProperty will do the work.

If you're want to know if the property exists anywhere, either on the object itself or up in the prototype chain, you can use the in operator.

if ('prop' in obj) {
  // ...
}

Eg.:

var obj = {};

'toString' in obj == true; // inherited from Object.prototype
obj.hasOwnProperty('toString') == false; // doesn't contains it physically

Underscore.js or Lodash

if (_.has(x, "y")) ...

:)


You can trim that up a bit like this:

if ( x.y !== undefined ) ...