Anjan Dutta
Javascript check if object has property
Javascript check if object has property
The best way of checking if a key exists in an object is to use the hasOwnProperty()
method.
let person = {name: 'John', age: 30, address: '18/1, Dover lane' };console.log(person.hasOwnProperty('address'));
This property returns true or false based upon the presence of that property.
Another way is to directly check the property by trying to access it.
For example:
let person = {name: 'John', age: 30, address: '18/1, Dover lane' };if (person.address) {.......// Your logic goes here.......}
Or like this:
if (person['address']) {.......// Your logic goes here.......}
The only drawback of the latter method is that we can’t be sure if the object property doesn’t exist or its value is set to null or undefined or false.