How to Get the Count of Properties in a JavaScript Object

In JavaScript, objects can be thought of as a collection of key-value pairs.
Objects are used to store data in a structured way, and can represent real-world objects, like a cat.
In some cases, it can be useful to know how many properties an object has.
In this post, we'll learn the two easiest ways to get the number of properties contained inside a JavaScript object.
Using a for loop
The most basic way to get the number of properties in an object is to use a for loop.
Essentially, you iterate over the properties and increment a counter for each property.
First, let's start with an example object:
const cat = {
name: "Fluffy",
age: 2,
color: "white",
isCute: true,
};
Next, we'll create a function that takes an object as an argument and returns the number of properties:
const getNumberOfProperties = obj => {
let count = 0;
for (const key in obj) {
count++;
}
return count;
}
The function takes an object as an argument and initializes a counter variable to 0.
Then, we use a for loop to iterate over the object's properties.
Let's use this function to get the number of properties in our cat object:
const cat = {
name: "Fluffy",
age: 2,
color: "white",
isCute: true,
};
const getNumberOfProperties = obj => {
let count = 0;
for (const key in obj) {
count++;
}
return count;
}
const count = getNumberOfProperties(cat);
console.log(count);
4
Using Object.keys()
Another way to get the number of properties in an object is to use the Object.keys() method.
This method returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would.
Once we have the array, we can just call the length property to get the number of properties.
Let's give it a try using our earlier example:
const cat = {
name: "Fluffy",
age: 2,
color: "white",
isCute: true,
};
const getNumberOfProperties = obj => {
return Object.keys(obj).length;
}
const count = getNumberOfProperties(cat);
console.log(count);
4
Conclusion
In this post, we learned two ways to get the number of properties in a JavaScript object.
The first way is to use a for loop, and the second way is to use the Object.keys() method.
Both methods are easy to understand, so you can choose the one that you prefer.
Thanks for reading!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!
Leave us a message!