CHAPTER 10
Maps and Sets
ES6 introduces two welcome data structures: maps and sets. Maps are similar to
objects in that they can map a key to a value, and sets are similar to arrays except that
duplicates are not allowed.
Maps
Prior to ES6, when you needed to map keys to values, you would turn to an object,
because objects allow you to map string keys to object values of any type. However,
using objects for this purpose has many drawbacks:
• The prototypal nature of objects means that there could be mappings that you
didn’t intend.
• There’s no easy way to know how many mappings there are in an object.
• Keys must be strings or symbols, preventing you from mapping objects to values.
• Objects do not guarantee any order to their properties.
The
Map
object addresses these deficiencies, and is a superior choice for mapping keys
to values (even if the keys are strings). For example, imagine you have user objects
you wish to map to roles:
const
u1
=
{
name
:
'Cynthia'
};
const
u2
=
{
name
:
'Jackson'
};
const
u3
=
{
name
:
'Olive'
};
const
u4
=
{
name
:
'James'
};
You would start by creating a map:
const
userRoles
=
new
Map
();
Then you can use the map to assign users to roles by using its
set()
method:
163