Table of Contents
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:
JAVASCRIPTconst 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:
JAVASCRIPTconst 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:
JAVASCRIPTconst 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);
BASH4
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:
JAVASCRIPTconst cat = {
name: "Fluffy",
age: 2,
color: "white",
isCute: true,
};
const getNumberOfProperties = obj => {
return Object.keys(obj).length;
}
const count = getNumberOfProperties(cat);
console.log(count);
BASH4
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!
How to Install Node on Windows, macOS and Linux
Managing PHP Dependencies with Composer
Getting Started with Svelte
Create an RSS Reader in Node
How to Serve Static Files with Nginx and Docker
How to build a Discord bot using TypeScript
How to deploy a PHP app using Docker
How to deploy a Deno app using Docker
Getting Started with Deno
Getting Started with Moment.js
Creating a Twitter bot with Node.js
Getting Started with Vuex: Managing State in Vue
