JavaScript map
When you want to store data which can be accessed by a key rather than looping over the data like Arrays
Or you wanted to create an alias. For example, you are storing an Array of some object which contains emails but you also wanted to store the name of that user.
Either you add the name attribute to the object or Instead create a map to get the name corresponding to the email. (Map will be helpful when the array of objects have common attribute values)
Syntax with Examples
let myMap = new Map();
or
let myFilledMap = new Map([
["key1", "value1"],
["key2", "value2"],
["key3", "value3"]
]);
The map is key-value pair like an Object. So to add a value we could do
myMap.set("redthemers@gmail.com","Red");
Here the first parameter is the key & the second is the value to be stored. and to retrieve the data I could use
myMap.get("redthemers@gmail.com");
To check if a value Exists
myMap.has("redthemers@gmil.com");
To Delete a particular value
myMap.delete("redthemers@gmail.com");
To clear everything from a Map we could do
myMap.clear();
Common Map Operations
map.get(key)
map.set(key,value)
map.has(key)
map.delete(key)
map.clear()
So InShort Its Similar to an Object & very useful.
For Practice
Open your browser console (f12 for chrome) and create a map add some properties. Now try to add a key that had already been added. See What Happens. Also, can we add an Object as a Key in Map?
Top comments (0)