© Russ Ferguson and Keith Cirkel 2017
Russ Ferguson and Keith CirkelJavaScript Recipes10.1007/978-1-4302-6107-0_11

11. Working with Maps

Russ Ferguson and Keith Cirkel2
(1)
Ocean, New Jersey, USA
(2)
London, UK
 

What Are the Advantages of Using a Map over an Object?

Problem

When is it better to use a map rather than an object?

Solution

While there are similarities to maps and objects, maps can contain both objects and primitives as keys or values.

The Code

var mapObj = new Map();
    mapObj.set('myString', 'myString is a string key');
    console.log(mapObj.get('myString')); //myString is a string key
var myObj = {};
    mapObj.set(myObj, 'Object is a used as a key');
    console.log(mapObj.get(myObj)); //Object is a used as a key
Listing 11-1.
Maps Can Use Different Types as Keys, Whereas Objects Use Strings

How It Works

Maps are similar to objects in that they have name/value pairs. Some of the methods associated with maps resemble the Set object (for more information on sets, see Chapter 10). One instance where maps are different than plain objects, is that map keys can be any value. In addition, the size of a map does not need to to be manually counted.

How Do You Add and Remove Elements of a Map?

Problem

You need to manage elements of a map.

Solution

Maps use the set method to set keys and values. Similar to the set object, it uses the delete method to remove a key.

The Code

var mapObj = new Map();
    mapObj.set('myString', 'myString is a string key');
    mapObj.delete('myString');
    console.log(mapObj.get('myString')); //undefined
Listing 11-2.
Adding and Removing Elements from a Map Object

How It Works

In Listings 11-1 and 11-2, the set method is used to create a key and its value. With the Map object, keys can be of any type. When using the set method, both keys and values are required properties. Keys can be updated by using the set method with the same key. The delete method will expect a key to delete the key/value pair from the object. If the element exists and has been deleted, the delete method will return true; otherwise it will return false.

How Do You Remove All the Elements of a Map?

Problem

You need to remove all elements of a Map object .

Solution

The clear method will remove all elements from a map, whereas delete will only remove one.

The Code

var mapObj = new Map();
    mapObj.set('myString', 'myString is a string key');
    mapObj.clear();
    console.log(mapObj.size); //returns 0
Listing 11-3.
Removing All Elements from a Set Object

How It Works

The Map object uses the same method name as a set. Using the clear method will remove all the elements from a Map object.

How Do You Determine If a Key Exists in a Map?

Problem

You need to find a key in the Map object.

Solution

Use the has key to check the existence of a key in the Map object.

The Code

var numberSet = new Set();
    numberSet.add(1);
    numberSet.add(2);
    numberSet.add(3);
    numberSet.add('things');  
    console.log(numberSet.keys());  //returns SetIterator {1, 2, 3, "things"}
    console.log(numberSet.values());  //returns SetIterator {1, 2, 3, "things"}
    var elements = numberSet.values();
    console.log(elements.next().value);  //returns 1
    console.log(elements.next().value);  //returns 2
Listing 11-4.
The Has Method Will Return True if an Element Exists

How It Works

The has method will return true only if the key exists as an element of the Map object.

How Do You Get All the Keys of a Map Object?

Problem

You want access to all the elements of a Map object.

Solution

The keys method will return a MapIterator object , which can be used to access all the elements of the Map object.

The Code

var mapObj = new Map();
    mapObj.set('1st value', '1st key');
    mapObj.set('2nd value', '2nd key');
    mapObj.set('3rd value', '3rd key');
    console.log(mapObj.keys()); //returns MapIterator object
var mapIterator = mapObj.keys();
    console.log(mapIterator.next().value); //1st value
    console.log(mapIterator.next().value); //2nd value
Listing 11-5.
The Keys Method Will Return a MapIterator Object That Lets You Access the Keys of Each Element

How It Works

The MapIterator object is returned from the keys method. In this example, it is saved as a separate variable. With the MapIterator saved as a separate variable, the next method lets you access each key that is in the Map object. There is no support for this method in Internet Explorer.

How Do You Get Access to the Value of Each Key Using the Values Method?

Problem

You want to use the values method of the Map object.

Solution

The values method works just like the keys method. The only difference is that you are returning the values of each element and not the key.

The Code

var mapObj = new Map();
    mapObj.set('1st value', '1st key');
    mapObj.set('2nd value', '2nd key');
    mapObj.set('3rd value', '3rd key');
    console.log(mapObj.values()); //returns MapIterator object
var mapIterator = mapObj.values();
    console.log(mapIterator.next().value); //1st key
    console.log(mapIterator.next().value); //2nd key
Listing 11-6.
The Values Method Returns an Iterator Object Just Like the Keys Method

How It Works

The results of calling the values method is the same as calling the keys method of a map. An iterator object is returned that can then be used to look at each value used in the Map object. In the previous example, the key of each element is being returned. Just like with the key element, there is no support for this in Internet Explorer.

How Can You Return Both the Key and Value from a Map Object?

Problem

You want to return both the key and value of an element from the Map object.

Solution

Using the entries method will return an array of a single key and value from the Map object using an Iterator object.

The Code

var mapObj = new Map();
    mapObj.set('1st value', '1st key');
    mapObj.set('2nd value', '2nd key');
    mapObj.set('3rd value', '3rd key');
    console.log(mapObj.entries()); //returns MapIterator object
var mapIterator = mapObj.entries();
    console.log(mapIterator.next().value); //["1st value", "1st key"]
    console.log(mapIterator.next().value); //["2nd value", "2nd key"]
Listing 11-7.
Looping Through a Set Using the forEach Method

How It Works

Using the last two examples as a base, the entries method will return an iterator object that can be used to access the elements of the Map object. In this case, it will return an array containing the key and value of each element. To access the next element in the object, the next method needs to be used. As with the other methods, this does not have support in Internet Explorer.

How Many Elements Are Currently in the Map Object?

Problem

You want to know the number of elements currently being used in the Map object.

Solution

The size property is similar to an array’s length property because it returns the number of elements being used in the Map object.

The Code

var mapObj = new Map();
    mapObj.set('1st value', '1st key');
    mapObj.set('2nd value', '2nd key');
    mapObj.set('3rd value', '3rd key');
    console.log(mapObj.size); //returns 3
Listing 11-8.
The Size Property Returns the Number of Elements in a Map

How It Works

Just like the length property of an array, the size property will return the number of elements that currently exist in a Map object.

How Do You Iterate Over a Map Using forEach?

Problem

You want to loop through each key in the map using forEach.

Solution

The forEach method works the same way as it does for the Set object. It will give you the ability to execute a callback once for each key.

The Code

var mapObj = new Map();
    mapObj.set('1st value', '1st key');
    mapObj.set('2nd value', '2nd key');
    mapObj.set('3rd value', '3rd key');
mapObj.forEach(function(value, key){
    console.log('mapObj['+key+'] = ' + value); //returns mapObj[N value] = N key
});
Listing 11-9.
The forEach Method Will Run a Function on Every Key on a Map

How It Works

Using forEach will ensure that a function will be called on every key that currently exists. The function can take the current value, its key, and the map as a whole as parameters each time the function is called.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.80.209