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’.

JavaScript
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.

check a key exists in JavaScript object

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.

Javascript
// 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

Similar Reads

Using in operator

The in operator in JavaScript checks if a key exists in an object by returning a boolean value. It verifies if the specified property is present within the object, simplifying key existence validation....

Using hasOwnProperty() method

The hasOwnProperty() method returns a boolean value that indicates whether the object has the specified property. The required key name could be passed in this function to check if it exists in the object....

Using the Object.keys method

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....

Using the typeof operator

Although it’s not a foolproof method for checking if a key exists in an object, you can use the typeof operator to check if a property is defined in an object. This method checks if the value associated with the key is not undefined....