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