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