JavaScript Program to Count the Number of Keys/Properties in an Object
Last Updated :
06 Mar, 2024
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:
Counting the Number of Keys using Object.keys
The Object.keys() method returns an array of a given object's enumerable properties, in the same order as they appear in the object. By retrieving the array of keys and calculating its length, we can determine the total number of keys in the object.
Syntax:
const keysArray = Object.keys(object);
const count = keysArray.length;
Example: Count the Number of keys using Object.keys() metod, here, we will count the number of keys in an object.
JavaScript
const user = {
name: "Aman",
age: 30,
email: "[email protected]",
address: {
street: "Sector 15 A-block",
city: "Noida",
state: "UP"
}
};
const keysArray = Object.keys(user);
// Count the number of keys
const count = keysArray.length;
console.log("Number of keys: " + count);
Explanation:
The code initializes an object `user` with nested properties. It extracts keys of `user` using `Object.keys()` and counts them. The count is logged to the console.
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: "[email protected]",
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);
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.
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: "[email protected]",
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);
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.
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);
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.
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);
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.
Similar Reads
JavaScript Program to Count the Occurrences of Each Character Here are the various methods to count the occurrences of each characterUsing JavaScript ObjectThis is the most simple and widely used approach. A plain JavaScript object (obj) stores characters as keys and their occurrences as values.JavaScriptconst count = (s) => { const obj = {}; for (const cha
3 min read
C# Program to Get the Count of Total Created Objects C# is a general-purpose programming language it is used to create mobile apps, desktop apps, websites, and games. In C#, an object is a real-world entity. Or in other words, an object is a runtime entity that is created at runtime. It is an instance of a class. In this article, we will create multip
3 min read
How to Get all Property Values of a JavaScript Object without knowing the Keys? To get all property values from a JavaScript object without knowing the keys involves accessing the object's properties and extracting their values.Below are the approaches to get all property values of a JavaScript Object:Table of ContentUsing Object.values() MethodUsing Object.keys() methodApproac
2 min read
How to get the size of a JavaScript object ? In this article, we will see the methods to find the size of a JavaScript object. These are the following ways to solve the problem: Table of Content Using Object.keys() methodUsing Object.objsize() methodUsing Object.entries() methodUsing Object.values() methodUsing Object.keys() methodWe can get t
2 min read
Find the Length of JavaScript object Finding the length of a JavaScript object refers to determining how many key-value pairs JavaScript object contains. This is often necessary when you need to know the size of the data structure for iterations, validations, or other operations involving object properties.1. Using the Object.keys() me
3 min read
How to Iterate JavaScript Object Containing Array and Nested Objects ? JavaScript provides us with several built-in methods through which one can iterate over the array and nested objects using the for...in loop, Object.keys(), Object.entries(), and Object.values(). Each method serves a distinct purpose in iterating over object properties, keys, and values which are ex
3 min read
How to Iterate Over Object Properties in TypeScript In TypeScript, Objects are the fundamental data structures that use key-value pair structures to store the data efficiently. To iterate over them is a common task for manipulating or accessing the stored data. TypeScript is a superset of JavaScript and provides several ways to iterate over object pr
3 min read
How to Print all Keys of the LinkedHashMap in Java? LinkedHashMap is a predefined class in Java that is similar to HashMap, contains a key and its respective value. Unlike HashMap, In LinkedHashMap insertion order is preserved. The task is to print all the Keys present in our LinkedHashMap in java. We have to iterate through each Key in our LinkedHas
2 min read
How to Check a Key Exists in JavaScript Object? Here are different ways to check a key exists in an object in JavaScript.Note: Objects in JavaScript are non-primitive data types that hold an unordered collection of key-value pairs. check a key exists in JavaScript object1. Using in Operator The in operator in JavaScript checks if a key exists in
2 min read
How to get a key in a JavaScript object by its value ? To get a key in a JavaScript object by its value means finding the key associated with a specific value in an object. Given an object with key-value pairs, you want to identify which key corresponds to a particular value, often for searching or data retrieval.How to get a key in a JavaScript object
4 min read