Categories
JavaScript Answers

How to Check if an Object has a Specific Property in JavaScript?

Spread the love

JavaScript objects are created dynamically.

This means that we may not know what content is in a JavaScript object.

Therefore, we’ve to find ways to check if an object contains a specific property.

In this article, we’ll look at how to check if an object has a specific property in JavaScript.

The hasOwnProperty Method

The hasOwnProperty is a method that are inherited from the Object.prototype .

Most objects inherit from them unless we specify them not to be inherited from it.

Therefore, we can write:

const obj = {
  a: 1,
  b: 2,
  c: 3
}

console.log(obj.hasOwnProperty('a'))
console.log(obj.hasOwnProperty('d'))

to call hasOwnProperty with the property name string.

The first console log should log true since a is in obj .

The second console log should log false since d is not in obj .

The hasOwnProperty method is inherited from Object.prototype , so it can easily be overwritten by other pieces of code.

To avoid this issue, we can call hasOwnProperty with call by writing:

const obj = {
  a: 1,
  b: 2,
  c: 3
}

console.log(Object.prototype.hasOwnProperty.call(obj, 'a'))
console.log(Object.prototype.hasOwnProperty.call(obj, 'd'))

We call hasOwnProperty with Object.prototype.hasOwnProperty.call which can’t be overwritten like with the hasOwnProperty method.

The first argument is the value of this , which should be set to the object we’re checking the property for.

And the 2nd argument is the property name string itself, which is the first argument of hasOwnProperty when we call it the first way.

Therefore, we should get the same result as before.

The in Operator

The in operator lets us check for non-inherited and inherited properties.

It’ll return true if there’s an inherited or non-inherited property with the given property name.

For instance, if we have:

const obj = {
  a: 1,
  b: 2,
  c: 3
}

console.log('a' in obj)
console.log('hasOwnProperty' in obj)

Then they both log true since a is in obj itself.

And hasOwnProperty is inherited from Object.prototype .

Lodash has Method

We can also use the Lodash has method to check if a property is a non-inherited property of an object.

For instance, if we write:

const obj = {
  a: 1,
  b: 2,
  c: 3
}

console.log(_.has(obj, 'a'))
console.log(_.has(obj, 'hasOwnProperty'))

Then the first console log logs true .

And the 2nd console log logs false .

Conclusion

There’re many ways to check if a property is in an object.

We can also distinguish them between inherited and non-inherited properties.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *