Introduction
Have you ever come up with a situation where you need to store a key and respective value in JavaScript? KeyValue Pair is really a very popular concept in C#, Java, or other languages. But in JavaScript, developers face challenges. Most of the time, they have to use custom types to address this issue.
Today, we will discuss "
Map" in JavaScript which is designed to serve the exact same purpose.
Example
Let's jump into the code directly. We will be creating a Map object here and use it in the whole example.
- var myMap = new Map();
- var key1 = "key1",key2="key2",key3="key3";
- myMap.set(key1, "value associated with key1");
- myMap.set(key2, 'value associated with key2');
- myMap.set(key3, 'value associated with key3');
- console.log(myMap.get(key1));
- console.log(myMap.get(key2));
- console.log(myMap.get(key3));
I created a Map object and assigned to myMap, as the first step. Then, I declared and initialized 3 variables - key1, key2, key3. I am trying to set the key values in created map object.
Syntax to set
- object.set(<key>, <value>);
As you can see in the example, I am setting the map using the following lines.
- myMap.set(key1, "value associated with key1");
- myMap.set(key2, 'value associated with key2');
- myMap.set(key3, 'value associated with key3');
- console.log(myMap.get(key1));
- console.log(myMap.get(key2));
- console.log(myMap.get(key3));
Here, I am assigning the key and values in the Map object and then logging the values for the keys.
The syntax for
get is shown below.
The output for the above code will be -
value associated with key1
value associated with key2
value associated with key3
Let's empty the Map completely by removing all the key-value pairs from the object.
This is the syntax for clear.
It removes all the keys and values from the object and makes the complete Map empty. If you will execute the following lines again,
- console.log(myMap.get(key1));
- console.log(myMap.get(key2));
- console.log(myMap.get(key3));
The output will be like the following.
undefined
undefined
undefined
Let's see how to remove a specific key from the Map. Let's initialize the application again.
Using the following code again,
- var key1 = "key1",key2="key2",key3="key3";
- myMap.set(key1, "value associated with key1");
- myMap.set(key2, 'value associated with key2');
- myMap.set(key3, 'value associated with key3');
Lets remove key "key2" from the Map using the following code.
This is the syntax for delete.
Let's now get all the keys from the Map object.
- var mapIter = myMap.keys();
Syntax for keys,
Finally, let's print all the keys and their respective values present in the Map object.
- for (var [key, value] of myMap) {
- console.log(key + ' = ' + value);
- }
Output
key1 = value associated with key1
key3 = value associated with key3
this for ... of is used in case of Map.
Please visit
here for complete example. Please let me know your feedback and questions if any.