How To Iterate Through JavaScript Objects

JavaScript

15/03/2021


Unlike arrays, JavaScript objects are not iterable. This means functions and statements like map(), forEach() or for..of will not work. If you attempt to do so, you'll be greeted with lovely errors such as TypeError: <Object>.forEach is not a function or TypeError: <Object> is not iterable.

However, there are a few ways to loop through an object, depending on whether you want its keys or values.

Let's take this object as an example:

JAVASCRIPT
const daysInMonth = {
January: 31,
February: 28,
March: 31,
}

Iterating over keys

You can easily obtain the keys/properties of an object with Object.keys().

JAVASCRIPT
Object.keys(daysInMonth)
// Array(3) [ "January", "February", "March" ]

As the output is an iterable object (i.e. array), you may then apply one of the above-mentioned methods or statements. However, there is also a way to directly iterate over your object using for...in.

JAVASCRIPT
for (let month in daysInMonth) {
console.log(month)
}
// January
// February
// March

Iterating over values

Similarly, to get the values of an object, you may use Object.values().

JAVASCRIPT
Object.values(daysInMonth)
// Array(3) [ 31, 28, 31 ]

Yet, to loop through the values, I prefer the following method:

JAVASCRIPT
for (let month in daysInMonth) {
console.log(daysInMonth[month])
}
// 31
// 28
// 31

WRITTEN BY

Code and stuff