Sunday, July 3, 2022
HomeWordPress Developmentiterate over an object in Javascript?

iterate over an object in Javascript?


It was throughout the preliminary days once I was studying Javascript, I at all times was once struck at some extent when Objects are concerned which is iterating over them. It additionally was once so confused at any time when I encountered an issue the place I needed to create a hashmap utilizing an empty Object.

This text offers you a transparent image about how one can and the way you can’t iterate over Objects in Javascript.

You can’t iterate over Javascript objects utilizing the common strategies like map(), forEach() or for..of loop.

Let there be an object:

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

Exit fullscreen mode

Utilizing map()

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

Exit fullscreen mode

You’re going to get an error saying TypeError: object.map is just not a perform

Utilizing forEach()

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

Exit fullscreen mode

You’ll once more arrive at an error saying TypeError: object.forEach is just not a perform

Utilizing for..of

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

Exit fullscreen mode

This offers you TypeError: object not iterable

So, how precisely are you able to iterate an object in Javascript?

Listed below are among the methods you are able to do that:

One of the easiest way is to make use of for..in loop

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

Exit fullscreen mode

However, personally I like to iterate over an object utilizing the Object.entries() methodology. This methodology generates an array of all of the enumerable properties of the item handed into it as an argument.

Since, it returns an array you should utilize any of the strategies you utilize to iterate over an array.

Utilizing map()

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

Exit fullscreen mode

Utilizing forEach()

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

Exit fullscreen mode

Utilizing for..of

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

Exit fullscreen mode

That is it! Eureka! With this text I’m certain you’ll always remember easy methods to iterate over Objects in Javascript.

I hope the article helps.

Attain me out on Github and LinkedIn.

Comply with me on Twitter

Have a pleasant day 🙂



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments