Open In App

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

Last Updated : 06 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

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.

Syntax:

const keysArray = Object.keys(object);
const count = keysArray.length;

Example: Count the Number of keys using Object.keys() metod, here, we will count the number of keys in an object.

Javascript




const user = {
    name: "Aman",
    age: 30,
    email: "Aman@example.com",
    address: {
        street: "Sector 15 A-block",
        city: "Noida",
        state: "UP"
    }
};
 
const keysArray = Object.keys(user);
 
// Count the number of keys
const count = keysArray.length;
 
console.log("Number of keys: " + count);


Output

Number of keys: 4


Explanation:

The code initializes an object `user` with nested properties. It extracts keys of `user` using `Object.keys()` and counts them. The count is logged to the console.

Counting the Number of Keys using for-in loop

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.

Syntax:

let count = 0; for (let key in object) {    }

Example: Count the Number of keys using for-in loop. Here, we will count the number of keys in an object using a loop

Javascript




const user = {
    name: "Aman",
    age: 30,
    email: "Aman@example.com",
    address: {
        street: "Sector-15 A-Block",
        city: "Noida",
        state: "Up"
    }
};
 
let count = 0;
for (let key in user) {
    if (user.hasOwnProperty(key)) {
        count++;
    }
}
 
console.log("Number of keys: " + count);


Output

Number of keys: 4


Explanation:

The code initializes an object `user` with nested properties. It iterates through each key of `user` using a for…in loop, increments the count if the property is an own property, and logs the count to the console.

Counting the Number of Keys using Object.getOwnPropertyNames

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.

Syntax:

const propertiesArray = Object.getOwnPropertyNames(object);
const count = propertiesArray.length;

Example: Count the Number of keys using Object.getOwnPropertyNames() . Here, we will count the number of keys in an object using the Object.getOwnPropertyNames() method.

Javascript




const user = {
    name: "Aman",
    age: 30,
    email: "Aman@example.com",
    address: {
        street: " Sector-15 A-Block",
        city: "Noida",
        state: "UP"
    }
};
 
const propertiesArray =
    Object.getOwnPropertyNames(user);
 
const count = propertiesArray.length;
 
console.log("Number of keys: " + count);


Output

Number of keys: 4


Explanation:

The code initializes an object `user` with nested properties. It retrieves all property names of `user`, including non-enumerable properties, using `Object.getOwnPropertyNames()`, then calculates the count. Finally, it logs the count to the console.

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.

Counting the Number of Keys using JSON.stringify

Using JSON.stringify() method converts the object to a JSON string and uses a regular expression match to count the occurrences of “:, representing the number of key-value pairs and properties.

Syntax:

JSON.stringify(value); 

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

Javascript




const user = {
    name: 'Aman',
    age: 30,
    city: 'Noida'
};
 
const count =
    JSON.stringify(user).match(/[^\\]":/g).length;
console.log("Number of keys :" + count);


Output

Number of keys :3


Explanation:

The code initializes an object `user` with properties. It converts the object to a JSON string using `JSON.stringify()`, then matches all occurrences of key-value pairs (excluding escaped double quotes) using a regular expression and calculates the count. Finally, it logs the count to the console.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads