How to iterate over object properties in JavaScript
Here's a very common task: iterating over an object properties, in JavaScript
If you have an object, you can’t just iterate it using map()
, forEach()
or a for..of
loop.
You will get errors:
const items = {
'first': new Date(),
'second': 2,
'third': 'test'
}
map()
will give you TypeError: items.map is not a function
:
items.map(item => {})
forEach()
will give you TypeError: items.forEach is not a function
:
items.forEach(item => {})
for..of
will give you TypeError: items is not iterable
:
for (const item of items) {}
So, what can you do to iterate?
for..in
is a simpler way:
for (const item in items) {
console.log(item)
}
You can also call Object.entries()
to generate an array with all its enumerable properties, and loop through that, using any of the above methods:
Object.entries(items).map(item => {
console.log(item)
})
Object.entries(items).forEach(item => {
console.log(item)
})
for (const item of Object.entries(items)) {
console.log(item)
}
→ I wrote 17 books to help you become a better developer:
- C Handbook
- Command Line Handbook
- CSS Handbook
- Express Handbook
- Git Cheat Sheet
- Go Handbook
- HTML Handbook
- JS Handbook
- Laravel Handbook
- Next.js Handbook
- Node.js Handbook
- PHP Handbook
- Python Handbook
- React Handbook
- SQL Handbook
- Svelte Handbook
- Swift Handbook
Also, JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025