DEV Community

Red
Red

Posted on • Originally published at redthemers.tech

JavaScript : Create Map to Store Key Value Pair

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();
Enter fullscreen mode Exit fullscreen mode

or

    let myFilledMap = new Map([
    ["key1", "value1"],
    ["key2", "value2"],
    ["key3", "value3"]
    ]);
Enter fullscreen mode Exit fullscreen mode

The map is key-value pair like an Object. So to add a value we could do

    myMap.set("redthemers@gmail.com","Red");
Enter fullscreen mode Exit fullscreen mode

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");
Enter fullscreen mode Exit fullscreen mode

To check if a value Exists

    myMap.has("redthemers@gmil.com");
Enter fullscreen mode Exit fullscreen mode

To Delete a particular value

    myMap.delete("redthemers@gmail.com");
Enter fullscreen mode Exit fullscreen mode

To clear everything from a Map we could do

    myMap.clear();
Enter fullscreen mode Exit fullscreen mode

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)