How to use the Object.keys method In Javascript
The Object.keys method in JavaScript retrieves an array of the object’s keys. By checking if the desired key is included in this array, one can determine if it exists in the object.
Syntax:
Object.keys(obj);
Example: In this example, we check if the key age exists in the object obj’. It uses Object.keys method to retrieve the keys and includes a method to check the presence of ‘age’.
const obj = {
name: 'Sandeep',
age: '32'
};
if (Object.keys(obj).includes('age')) {
console.log('true');
} else {
console.log('false');
}
Output
true
How to Check a Key Exists in JavaScript Object ?
Checking if a key exists in a JavaScript object involves verifying whether a specific property is defined within the object. This practice ensures data integrity, prevents errors, and facilitates smooth program execution by confirming property existence before accessing or manipulating it.
Objects in JavaScript are non-primitive data types that hold an unordered collection of key-value pairs. Here, we have an object and we need to check whether the given key is present in the given object or not.
Lets create a JavaScript object having with given key-values and then we will explore different approaches to check a key exist in the Object.
// Given object
let exampleObj = {
id: 1,
remarks: 'Good'
}
Here are some common approaches to Check if a Key Exists in an Object:
Table of Content
- Using in operator
- Using hasOwnProperty() method
- Using the Object.keys method
- Using the typeof operator
Contact Us