Counting the Number of Keys using JSON.stringify
Using JSON.stringify() method converts the object to a JSON string and uses a regular expression match to count the occurrences of “:, representing the number of key-value pairs and properties.
Syntax:
JSON.stringify(value);
Example: Count the Number of keys using JSON.stringify() method. Here, we are using the above-explained approach.
Javascript
const user = { name: 'Aman' , age: 30, city: 'Noida' }; const count = JSON.stringify(user).match(/[^\\] ":/g).length; console.log(" Number of keys :" + count); |
Number of keys :3
Explanation:
The code initializes an object `user` with properties. It converts the object to a JSON string using `JSON.stringify()`, then matches all occurrences of key-value pairs (excluding escaped double quotes) using a regular expression and 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