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