1. Code
  2. Coding Fundamentals

How to Iterate Over Object Keys With JavaScript

Scroll to top

Custom objects cannot be iterated over using the for...of loop. In addition, you can't use iterator methods like map() and forEach(). If you do, you'll get a TypeError in every instance. 

Instead, use for...in to iterate over objects. This method iterates over all of the object's enumerable, non-symbol properties.

In the following example, we use it to iterate over all three properties of obj, and for each property, we log a string consisting of the property name (i.e. its key) and its corresponding value.

1
var obj = {a: 1, b: 2, c: 3};
2
3
for (const prop in obj) {
4
  console.log(`obj.${prop} = ${obj[prop]}`);
5
}
6
7
// Output:

8
// "obj.a = 1"

9
// "obj.b = 2"

10
// "obj.c = 3"

We initialized the loop with a variable, prop, which will hold a different property name (aka key) on each iteration of the object properties. The code specified within the block will run on each iteration.

Here's a little demo to demonstrate that (click on Result to see the output):

Inside the loop, on every iteration, we log one of the object's property names and values to the console.

Another way to iterate over an object's properties is by passing the object inside Object.entries() and calling the method. This will return all the enumerable properties of that object inside a multidimensional array (array of arrays):

1
const obj = {a: 1, b: 2, c: 3};
2
3
let result = Object.entries(obj)
4
5
console.log(result)
6
// [["a", 1], ["b", 2], ["c", 3]]

Then we can loop through that using any of the array iterator methods:

1
Object.entries(obj).forEach(entry => {
2
  // do something

3
})
4
5
Object.entries(obj).map(entry => {
6
  // do something

7
})
8
9
Object.entries(obj).every(entry => {
10
  // do something

11
})
12
13

You can also use a for...of loop:

1
for (const entry of Object.entries(obj)) {
2
  // do something
3
}
4
5
for (const [key, value] of Object.entries(obj)) {
6
  // do something
7
}

Here are some demos:

Here, because we get an array consisting of the key and value on each iteration, we simply access them with entry[0] and entry[1] respectively. If you want just the keys instead of the key and value, use Object.keys() in place of Object.entries().

for...of is basically the same:

Conclusion

These are the ways we can easily iterate over an object's properties and keys in JavaScript. Check out our JavaScript posts for more articles and tutorials.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.