Table of Contents
In JavaScript, objects can be thought of as a collection of key-value pairs. The keys are strings and the values can be any type of data.
The type of data can be anything ranging from a string, number, boolean, array, object, function, or even another object.
In this article, we will look at all the different ways you can iterate over the key-value pairs of an object in JavaScript.
Iterating using entries()
The most common way to iterate over an object is using the entries()
method. This method returns an array of key-value pairs of the object, which we can then iterate over.
Let's first start with our example object:
JAVASCRIPTconst object = {
city: "New York",
state: "New York",
country: "USA"
};
Now let's use the entries()
method to get an array of key-value pairs:
JAVASCRIPTconst object = {
city: "New York",
state: "New York",
country: "USA"
};
const entries = Object.entries(object);
console.log(entries);
BASH[ [ 'city', 'New York' ], [ 'state', 'New York' ], [ 'country', 'USA' ] ]
Now we can just iterate over this like any other array:
JAVASCRIPTconst object = {
city: "New York",
state: "New York",
country: "USA"
};
const entries = Object.entries(object);
for (const [key, value] of entries) {
console.log(`${key}: ${value}`);
}
BASHcity: New York
state: New York
country: USA
Iterating using for...in
Another way to iterate is to instead use the for...in
loop. This loop will iterate over the keys of the object.
You can then take this key and use it to get the corresponding value:
JAVASCRIPTconst object = {
city: "New York",
state: "New York",
country: "USA"
};
for (const key in object) {
console.log(`${key}: ${object[key]}`);
}
BASHcity: New York
state: New York
country: USA
This method is a bit less verbose and more readable than the entries()
method.
Conclusion
In this post, we learned how to iterate over the key-value pairs of an object in JavaScript.
You can either use the entries()
method or the for...in
loop and then iterate through each of the key-value pairs.
Thanks for reading!
- How to Install Node on Windows, macOS and Linux
- How to Set Up Cron Jobs in Linux
- How to deploy a Node app using Docker
- Getting Started with Sass
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Handlebars.js
- Getting User Location using JavaScript's Geolocation API
- Learn how to build a Slack Bot using Node.js
- Using Push.js to Display Web Browser Notifications
- Using Axios to Pull Data from a REST API
- How To Create a Modal Popup Box with CSS and JavaScript