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