Table of Contents
Objects in JavaScript can be thought of as a collection of key-value pairs.
The keys are strings and the values can be anything like strings, numbers, arrays, objects, and functions.
The commonly-used forEach is great for iterating over an array, but it doesn't work directly on objects because objects are not arrays.
In this post, we'll learn how you can use the forEach method to iterate over an object.
How to use forEach on an object
The forEach method is called on an array and takes a callback function as an argument.
This callback function is then called for each item in the array.
Here's how it looks like on an array:
JAVASCRIPTconst array = [1, 2, 3];
array.forEach(item => {
console.log(item);
});
BASH1
2
3
Now let's define an example object:
JAVASCRIPTconst object = {
name: "Sabe.io",
url: "https://sabe.io"
};
As mentioned before, using the forEach method on an object will not work:
JAVASCRIPTconst object = {
name: "Sabe.io",
url: "https://sabe.io"
};
object.forEach(item => {
console.log(item);
});
BASHUncaught TypeError: object.forEach is not a function
To iterate over an object, we need to use the Object.keys method to get all of the keys.
Then we can use the forEach method on the keys array:
JAVASCRIPTconst object = {
name: "Sabe.io",
url: "https://sabe.io"
};
Object.keys(object).forEach(key => {
console.log(key);
});
BASHname
url
You can also use these keys to get the values:
JAVASCRIPTconst object = {
name: "Sabe.io",
url: "https://sabe.io"
};
Object.keys(object).forEach(key => {
console.log(object[key]);
});
BASHSabe.io
https://sabe.io
Alternatively, you can just iterate only the values directly using the Object.values method:
JAVASCRIPTconst object = {
name: "Sabe.io",
url: "https://sabe.io"
};
Object.values(object).forEach(value => {
console.log(value);
});
BASHSabe.io
https://sabe.io
Finally, you can also use the entries object to get both the keys and values:
JAVASCRIPTconst object = {
name: "Sabe.io",
url: "https://sabe.io"
};
Object.entries(object).forEach(([key, value]) => {
console.log(key, value);
});
BASHname Sabe.io
url https://sabe.io
Conclusion
In this post, we learned how to use the forEach method to iterate over an object.
We can either use the Object.keys method to get the keys and then use the forEach method on the keys array, or we can use the Object.values method to get the values directly, or use Object.entries to get both the key and the value from the object.
Thanks for reading!
Managing PHP Dependencies with Composer
Getting Started with Express
Getting Started with Electron
How to deploy a .NET app using Docker
Best Visual Studio Code Extensions for 2022
How to build a Discord bot using TypeScript
Getting Started with Deno
How to deploy a MySQL Server using Docker
Getting Started with Handlebars.js
Getting Started with Moment.js
Creating a Twitter bot with Node.js
Using Axios to Pull Data from a REST API
