Example 1: Count the Number of Key in an Object Using for...in
Output
3
The above program counts the number of keys/properties in an object using the for...in loop.
The count variable is initially 0. Then, the for...in loop increases the count by 1 for every key/value in an object.
Note: While using the for...in loop, it will also count inherited properties.
For example,
If you only want to loop through the object's own property, you can use the hasOwnProperty() method.
if (student.hasOwnProperty(key)) {
++count:
}
Example 2: Count the Number of Key in an Object Using Object.key()
Output
3
In the above program, the Object.keys() method and the length property are used to count the number of keys in an object.
The Object.keys() method returns an array of a given object's own enumerable property names i.e. ["name", "age", "hobbies"].
The length property returns the length of the array.