In this short post we are going to take a brief look at the ways in which you can use the Array.prototype.forEach method to get the key value pairs from an object.
If you want to read more into how you can use the JavaScript forEach method with an object I recommend taking a look at my post about it here.
Let’s now look at how you can get the JavaScript forEach key value pairs from an object
How to get the JavaScript forEach key value pairs from an object
The first and easiest way to get the key value pairs from an object with the JavaScript forEach method is by combining it with Object.entries.
Here is an example of how to get the JavaScript forEach key value pairs from an object with Object.entries:
const myObj = { a: 1, b: 2, c: 3 }
Object.entries(myObj).forEach(([key, value]) => {
console.log(key, value)
})
// "a", 1
// "b", 2
// "c", 3
In the above example we are using Object.entries to first convert the object into an array of key value pairs.
We then use forEach with the array of key value pairs so that we can iterate through each of them. The key value pairs in the array are stored as an array as well, the first index will be relating to the key and the second index relating to the value.
All we have to do from there is to destructure the key value pair array and save the first index as a variable named key and the second as the value and then we have access to the key value pairs using the JavaScript forEach method.
Using Object.keys with forEach to get the key value pairs
Another option is to use Object.keys with forEach instead of using Object.entries.
The main difference here is that instead of getting an array of key value pairs from an object we will instead be given an array of keys which we can then use to perform a lookup on the object to get the value.
Here is how this will look:
const myObj = { a: 1, b: 2, c: 3 }
Object.keys(myObj).forEach(key => {
const value = myObj[key]
console.log(key, value)
})
// "a", 1
// "b", 2
// "c", 3
As you can see this ends up giving us the same result.
If you want to learn more about the various ways to use forEach with an object you can find out more here.
Summary
There we have how to get the JavaScript forEach key value pairs from an object, if you want more like this be sure to check out some of my other posts!