Skip to content

How to iterate over object properties in JavaScript

New Course Coming Soon:

Get Really Good at Git

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)
}
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Get my JavaScript Beginner's Handbook
→ Read my JavaScript Tutorials on The Valley of Code
→ Read my TypeScript Tutorial on The Valley of Code

Here is how can I help you: