Loop through objects and arrays in JavaScript. A simple guide.
Oct 19, 2020
There are countless ways to iterate through JS objects and arrays. Here’s how to do it in the simplest way, with ES6 and beyond, for each purpose.
Objects
Keys and values
Loop through keys and values of an object.
Keys
Loop through keys of an object.
Values
Loop through values of an object.
Arrays
Loop through an array.
Return
If you want to return
the items or the whole loop, you have to swap the forEach
for a map
. You can change it in any of the examples above, it will work as expected, and the result will be returned. A forEach
will always return undefined
.