How to use forEach with Key Value Pairs Object in JavaScript

Updated onbyAlan Morel
How to use forEach with Key Value Pairs Object in JavaScript

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:

JAVASCRIPT
const array = [1, 2, 3]; array.forEach(item => { console.log(item); });
BASH
1 2 3

Now let's define an example object:

JAVASCRIPT
const object = { name: "Sabe.io", url: "https://sabe.io" };

As mentioned before, using the forEach method on an object will not work:

JAVASCRIPT
const object = { name: "Sabe.io", url: "https://sabe.io" }; object.forEach(item => { console.log(item); });
BASH
Uncaught 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:

JAVASCRIPT
const object = { name: "Sabe.io", url: "https://sabe.io" }; Object.keys(object).forEach(key => { console.log(key); });
BASH
name url

You can also use these keys to get the values:

JAVASCRIPT
const object = { name: "Sabe.io", url: "https://sabe.io" }; Object.keys(object).forEach(key => { console.log(object[key]); });
BASH
Sabe.io https://sabe.io

Alternatively, you can just iterate only the values directly using the Object.values method:

JAVASCRIPT
const object = { name: "Sabe.io", url: "https://sabe.io" }; Object.values(object).forEach(value => { console.log(value); });
BASH
Sabe.io https://sabe.io

Finally, you can also use the entries object to get both the keys and values:

JAVASCRIPT
const object = { name: "Sabe.io", url: "https://sabe.io" }; Object.entries(object).forEach(([key, value]) => { console.log(key, value); });
BASH
name 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!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.