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:
JAVASCRIPT
const object = {
city: "New York",
state: "New York",
country: "USA"
};
Now let's use the entries() method to get an array of key-value pairs:
JAVASCRIPT
const object = {
city: "New York",
state: "New York",
country: "USA"
};
const entries = Object.entries(object);
console.log(entries);