Check if a key exists in an object in Javascript
Check if a key exists in an object in Javascript
In this chapter, you will learn about how to check if a exists in an object in Javascript. The Javascript provides some inbuilt methods to check whether key or property exists in the object. The key of an object can also be called as property.
Solution 1:
We can use in operator to check whether a key exists in an object or not, let write an example for the same.
let person = { name: 'John', email: 'John@john.com' } let isNameKeyExist = 'name' in person; let isEmailKeyExist = 'email' in person; let isAddressKeyExist = 'address' in person; console.log(isNameKeyExist); console.log(isEmailKeyExist); console.log(isAddressKeyExist); // Output // true // true // false
Solution 2:
hasOwnProperty(): You can also use the method hasOwnProperty(), it returns a boolean value indicating whether the object has the specified property as its own property. Let’s write an example of the same.
let person = { name: 'John', email: 'John@john.com' } let isNameKeyExist = person.hasOwnProperty('name'); let isEmailKeyExist = person.hasOwnProperty('email'); let isAddressKeyExist = person.hasOwnProperty('address'); console.log(isNameKeyExist); console.log(isEmailKeyExist); console.log(isAddressKeyExist); // Output // true // true // false
Solution 3:
typeof: We can also use the typeof operator, which returns a string indicating the type of the unevaluated operand. Let’s write an example for the same
let person = { name: 'John', email: 'John@john.com' } if ( typeof(person["name"]) === "undefined" ) console.log('The key name doesnot exist'); else console.log('The key name exist'); if ( typeof(person["email"]) === "undefined" ) console.log('The key email doesnot exist'); else console.log('The key email exist'); if ( typeof(person["address"]) === "undefined" ) console.log('The key address doesnot exist'); else console.log('The key address exist'); // Output // The key name exist // The key email exist // The key address doesnot exist