DEV Community

Rakshit
Rakshit

Posted on • Updated on

How to iterate over an object in Javascript?

It was during the initial days when I was learning Javascript, I always used to be struck at a point when Objects are involved which is iterating over them. It also used to be so confused whenever I encountered a problem where I had to create a hashmap using an empty Object.

This article will give you a clear picture about how you can and how you cannot iterate over Objects in Javascript.

You cannot iterate over Javascript objects using the regular methods like map(), forEach() or for..of loop.

Let there be an object:

const object = {
    name: 'Rakshit',
    age: 23,
    gender: 'Male'
}
Enter fullscreen mode Exit fullscreen mode

Using map()

object.map(obj => {})
Enter fullscreen mode Exit fullscreen mode

You will get an error saying TypeError: object.map is not a function

Using forEach()

object.forEach(obj => {})
Enter fullscreen mode Exit fullscreen mode

You will again arrive at an error saying TypeError: object.forEach is not a function

Using for..of

for (const obj of objects) {}
Enter fullscreen mode Exit fullscreen mode

This will give you TypeError: object not iterable

So, how exactly can you iterate an object in Javascript?

Here are some of the ways you can do that:

One of the most simplest way is to use for..in loop

for(const obj in object) {}
Enter fullscreen mode Exit fullscreen mode

But, personally I love to iterate over an object using the Object.entries() method. This method generates an array of all the enumerable properties of the object passed into it as an argument.

Since, it returns an array you can use any of the methods you use to iterate over an array.

Using map()

Object.entries(object).map(obj => console.log(obj))
Enter fullscreen mode Exit fullscreen mode

Using forEach()

Object.entries(object).forEach(obj => console.log(obj))
Enter fullscreen mode Exit fullscreen mode

Using for..of

for (const obj of Object.entries(object)) {
  console.log(obj)
}
Enter fullscreen mode Exit fullscreen mode

That's it! Eureka! With this article I am sure you will never forget how to iterate over Objects in Javascript.

I hope the article helps.

Reach me out on Github and LinkedIn.

Follow me on Twitter

Have a nice day :)

Discussion (9)

Collapse
lukeshiru profile image
Luke Shiru • Edited on

Don't forget about Object.fromEntries to turn it back into an object:

Object.fromEntries(
    Object.entries({ foo: 1, bar: 2 }).map(([key, value]) => [key, value * 2]),
); // { foo: 2, bar: 4 }
Enter fullscreen mode Exit fullscreen mode

Cheers!

Collapse
rakshit profile image
Rakshit Author

Thanks :)

Collapse
peerreynders profile image
peerreynders • Edited on

I encountered a problem where I had to create a hashmap using an empty Object.

An object is only really viable if you are using strings (or symbols) as keys. Anything else is coerced to a string with .toString() including numbers.

So consider using a Map instead (it's an iterable so it can be directly iterated).

const map = new Map([
  ['name', 'Rakshit'],
  ['age', 23],
  ['gender', 'Male'],
]);

for (const [key, value] of map) {
  console.log(`${key}: ${value}`);
}
Enter fullscreen mode Exit fullscreen mode

Map - JavaScript | MDN

The Map object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values) may be used as either a key or a value.

favicon developer.mozilla.org
Collapse
rakshit profile image
Rakshit Author

Makes sense, thank you so much :)

Collapse
rickdelpo1 profile image
Rick Delpo

The explanation as to why u cannot iterate over an object is because u need to transform the object into an array first then u can use the .forEach method on the array with either Object.keys(), Object.values(), or Object.entries().

Arrays imho are by far the most important data type !!

Collapse
peerreynders profile image
peerreynders

Arrays imho are by far the most important data type !!

I argue that the iteration protocols are far more generally applicable.

Array methods are limited to arrays, which means you always have to transform something to an array before you can do anything via array methods.

Unfortunately the current generation of IDEs makes it incredibly easy to discover methods-on-classes rather than functions-that-can-be-applied-to-a-type. That fosters an environment where methods are favoured, leading to array methods being trendy while for…of is being judged as "old school" even when it is entirely appropriate within JavaScript's scope.

One big advantage of the iteration protocol is that it can be implemented in a lazy fashion—when appropriate—which is simply not possible with array methods; with arrays you are forced to render the collection in full before you can start working on any item.

In the absence of iteration protocol support the .forEach() method is supported in a lot of surprising places (though I'm personally not a fan).

Collapse
rickdelpo1 profile image
Rick Delpo

we can use Object.keys with method .forEach

Object.keys(object).forEach(key => {
console.log(key, object[key]);
});

Collapse
rakshit profile image
Rakshit Author

Thanks. Would be of great use for those who read this article :)

Collapse
audreyminer profile image
AudreyMiner

How do I enumerate a JavaScript object? pelvic floor clinic calgary