Thursday, May 19, 2022

How To Iterate Over Object Keys With JavaScript

How To Iterate Over Object Keys With JavaScript

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 (ie. its key) and its corresponding value.

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):

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

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

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.


No comments:

Post a Comment