Tip 14: Iterating over Key-Value Data with Map & Spread Operator

In this tip, you’ll learn how to iterate directly over key-value data in maps with either loops or the spread operator.

In the previous tip, you saw how maps are an improved key-value collection when you’re regularly adding or deleting items. As you saw, objects are very useful, but there are times when a map has distinct advantages. You can see those advantages on the Mozilla Developer Network.

You’ve already explored several advantages pertaining to when keys are set. Now you’re going to explore another suggested usage for maps: collections that are iterated.

Looping over objects

Objects are very frustrating to iterate over. In fact, there used to be no way to directly iterate over them. You were always forced to transform them before you could loop over the data. Things are a little better. You can now use a for...in loop to iterate over objects, but you’ll have access only to the object key. In a way, it’s not much different from looping over an array of keys. Check out Tip 27, Reduce Loop Clutter with for…in and for…each, for more about the for...in loop.

As you can see. Looping over objects is complicated. Conversely, you can iterate over maps directly.

Start by returning to your filters. Suppose you have an object of filters and you want to list the applied filters. After all, you want your users to remember they’re seeing a subset of information. How would you write code that translates the objects to a string?

How would you, for example, transform all the key-values to be a string of the form “key:value”?

The odd thing is you won’t iterate over the filters object. Instead, you’ll pull out other information and then iterate over that.

Get hands-on with 1200+ tech skills courses.