The best method to do this is by using Object.entries because the entries method will return the object properties as key value pairs in the form of an array.
When we combine this with the forEach method it means we can then effectively use forEach with an Object for iterating through the keys and values of an object.
As you can see we have already been able to make use of forEach to be able to iterate through the properties of an object by first converting it into an array using Object.entries and then getting the key value pairs from it.
In the above example of Object.entries with forEach you will notice that the argument that we are accepting is
[key, value] that is because we are destructuring an array.
When using Object.entries, it will convert the object into an array of key value pairs which are stored as nested arrays with a total of 2 array items in each, the key and the value.
The first index in one of these nested arrays will be the key and the second index will be the value.
So for example:
const objectEntries = [["someKey", "some value"]] const firstEntry = objectEntries const key = firstEntry const value = firstEntry
Using Object.keys will return all the keys of an object as an iterable array.
The reason why the Object.keys method works is because we can perform a lookup with each key in the array to find the value so that we end up with both the key and the value if needed.
Here is an example of how to use Object.keys with forEach to get the key value pairs:
As you can see this method of using Object.keys with forEach works because we get an array of all the keys in the object that when we iterate through using forEach we can use each key to perform a lookup on the original object to then get the value from as well.
Using Object.values works in a similar way to Object.keys but instead of getting an array of the keys you get an array of the values from the object.
Using Object.values generally will have less use cases than the Object.entries or Object.keys because you can’t relate it to a key afterwards which means you can’t perform any further lookups.
With that said, if you just want to iterate through the values of an object using forEach then Object.values is perfect for it because it will provide all the values in a given object as an array that you can then loop through using Array.prototype.forEach.
Now we have covered how to use forEach with an object by converting it to an array, let’s take a look at how we can improve on this and create our own helper method.
For the most part, you probably won’t need to create your own helper method because using Object.entries with Array.prototype.forEach is pretty concise and doesn’t add much overhead, but there might be the odd occasion where it is useful.
As you can see, creating a helper method to be able to convert an object to an array and then loop over it using forEach is pretty easy to do.