Tip 13: Update Key-Value Data Clearly with Maps
In this tip, you’ll learn how to use the Map object for key-value collections of frequently updated data.
In Tip 10, Use Objects for Static Key-Value Lookups, you learned
that you should only use objects deliberately and not as a default collection.
Now you’re going to get a chance to look at an alternative: Map
.
Map
Map is a special kind of collection that can do certain things very easily. The Mozilla Developer Network has a nice list of circumstances where Map is a better option for a collection than a plain object. I encourage you to read the full list, but this tip examines two specific situations:
-
Key-value pairs are frequently added or removed.
-
A key isn’t a string.
In the next tip, you’ll see another big advantage: using Map for iterating over collections. For now, you just need to be familiar with adding or removing values to maps.
Adding & removing key-value pairs: Example
First, think about what it means that key-value pairs are frequently added and removed. Consider a pet adoption website. The site has a list of all the adorable dogs that need homes. Because people have different expectations of their pets (some want big dogs, some like certain breeds), you’ll need to include a way to filter the animals.
You’ll start off with a collection of animals:
Get hands-on with 1400+ tech skills courses.