Counting the Number of Keys using Object.entries

JavaScript Object.entries() method is used to return an array consisting of enumerable property [key, value] pairs of the object which are passed as the parameter.

Syntax:

Object.entries(obj); 

Example: Count the Number of keys using Object.entries() method. Here, we are using the above-explained approach.

Javascript




const obj = {
    name: 'Aman',
    age: 30,
    city: 'Noida'
};
 
const count = Object.entries(obj).length;
console.log("Number of keys :" + count);


Output

Number of keys :3


Explanation:

The code initializes an object `obj` with properties. It converts the object into an array of key-value pairs using `Object.entries()`, retrieves the length of this array, representing the count of keys, and logs it to the console.

JavaScript Program to Count the Number of Keys/Properties in an Object

An object consists of key-value pairs where each key is a unique identifier associated with a corresponding value.

Several methods can be used to count the number of keys/properties in an object, which are listed below:

Table of Content

  • Counting the Number of Keys using Object.keys
  • Counting the Number of Keys using for-in loop
  • Counting the Number of Keys using Object.getOwnPropertyNames
  • Counting the Number of Keys using Object.entries
  • Counting the Number of Keys using JSON.stringify

Similar Reads

Counting the Number of Keys using Object.keys

The Object.keys() method returns an array of a given object’s enumerable properties, in the same order as they appear in the object. By retrieving the array of keys and calculating its length, we can determine the total number of keys in the object....

Counting the Number of Keys using for-in loop

...

Counting the Number of Keys using Object.getOwnPropertyNames

We can also use for-in loop to iterate over the properties of an object and increment a counter for each property encountered. This approach allows us to count the number of keys without relying on any built-in methods....

Counting the Number of Keys using Object.entries

...

Counting the Number of Keys using JSON.stringify

The Object.getOwnPropertyNames() method returns an array of all properties (including non-enumerable properties) found directly on a given object. We can obtain the array of property names and calculate its length to determine the total number of keys....

Contact Us