How to Iterate Over Object Properties in JavaScript

It is not possible to iterate over an object in JavaScript as you would with other iterables like strings and arrays using map(), forEach() or for of but it is possible to do it in another way, which is what we will look at in this tutorial.

 

Iterating using a for of and forEach()

Before we try a method of iteration that will work with objects, let's try a for of and a forEach() and see what happens.

 

Using forEach():

 

var fruit = {'apples': 2, 'strawberries': 2, 'oranges': 2}

fruit.forEach(myFunction)

function myFunction(value, index, fruit) {
  console.log(value)
}
Uncaught TypeError: fruit.forEach is not a function

 

And with for of:

 

var fruit = {'apples': 2, 'strawberries': 2, 'oranges': 2}

for (let f of fruit) {
  console.log(f)
}
Uncaught TypeError: fruit is not iterable

 

Not looking too good at the moment, so how can we iterate over the properties of an object in JavaScript?

 

for in

The solution is to use for in loop instead of a for of. With it, we can get the name of the property of an object on each iteration.

 

var fruit = {'apples': 2, 'strawberries': 2, 'oranges': 2}

for (let f in fruit) {
  console.log(f)
}
apples
strawberries
oranges

 

Accessing the Value of an Object in a for in Loop

We can access the values of a property in an object by passing the property name inside [] (square brackets) on the object variable.

 

var fruit = {'apples': 2, 'strawberries': 2, 'oranges': 2}

for (let f in fruit) {
  console.log(fruit[f])
}
2
2
2

 

Using Object.keys()

Another approach is to turn the property names of an object in an array. This can be done using the Object.keys() method.

 

var fruit = {'apples': 2, 'strawberries': 2, 'oranges': 2}

console.log(Object.keys(fruit))
["apples", "strawberries", "oranges"]

 

Conclusion

You now know how to iterate over object properties in JavaScript.

object iterate