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!
- Getting Started with TypeScript
- Getting Started with Electron
- Best Visual Studio Code Extensions for 2022
- How to deploy a Deno app using Docker
- How to deploy a MySQL Server using Docker
- How to deploy a Node app using Docker
- Getting User Location using JavaScript's Geolocation API
- Getting Started with Moment.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Setting Up Stylus CSS Preprocessor
- Setting Up a Local Web Server using Node.js
- How To Create a Modal Popup Box with CSS and JavaScript