JavaScript Map

Map is combination of key and value pair. Here key can be a primitive data type value or any other object. Map is generally a data structure in Javascript.

new Map()
new Map([iterable])
//Create an empty map
let firstMap = new Map();
//Initialize a map with element
//Using array of [key, value] pairs
let secondMap = new Map([
    ['Fruit',"Mango"],
    ["Error",404],
    [true,"Instruction"]
  ]);
console.log(firstMap);
console.log(secondMap);
map data structure example
Map {}
Map { 'Fruit' => 'Mango', 'Error' => 404, true => 'Instruction' }

That is basic methods which are create a map. You'll can also use Object.entries(). Which is returning an array that is combination of key value pairs.

//Create a map using Object.entries
let map = new Map(Object.entries({
  code:"JavaScript",
  error:"Missing value",
  browser:"Chrome"  ,
}));
console.log(map);
Map {
  'code' => 'JavaScript',
  'error' => 'Missing value',
  'browser' => 'Chrome' }

Map method and properties

Method Overview
map.set(key,value) Add element to an map
map.get(key) Get an element by a key, undefined when key not found
map.has(key) Returns true value when key element are exist, otherwise false
map.delete(key) Remove given key element from map
map.size Return number of element
map.clear() Clears all element from the map
map.entries() returns an iterable for a entries of (key and value) pair
map.values() returns an iterable value pair
map.keys() returns an iterable keys pair

map.set(key,value)

This method are used to add a element in map. When given key value are already exist in map. In this situation this method are modified new value to existing key.

//Create a map
let map = new Map([["Project","007"]]);
console.log(map);

//Add a new element
map.set("User","Admin");
console.log(map);

//Modified User key value
map.set("User","Manager");
console.log(map);
Map { 'Project' => '007' }
Map { 'Project' => '007', 'User' => 'Admin' }
Map { 'Project' => '007', 'User' => 'Manager' }

map.get(key)

That is an simplest method which are return map element value by using of particular key. When key are not exist then this method are return undefined value.

//Create an empty map
let map = new Map([["Project","007"]]);

console.log("Project : ",map.get("Project"));
console.log("Project : ",map.get("secretProject"));
Project :  007
Project :  undefined

map.has(key)

This method are used to check given map key element are exist or not exist. When element is exist (found) then its returns a boolean true value, otherwise return false value.

//Create a map called company
let company = new Map([
  ["Tester","100"],
  ["Programmer","10000"],
  ["Client","100000"]
]);
//Check existence using has() method
console.log("Client is Exist ? ",company.has("Client"));

console.log("Programmer is Exist ? ",company.has("Programmer"));

console.log("Partner is Exist ? ",company.has("Partner"));
Client is Exist ?  true
Programmer is Exist ?  true
Partner is Exist ?  false

map.delete(key)

This method are used to delete an element of map. This operation is based on a map key value, when key is existed, Then in this case this method are delete that element. Otherwise this method not remove any element.

//Create a map
let company = new Map([
  ["Tester","100"],
  ["Programmer","10000"],
  ["Client","100000"],
  ["Partner","5"],
  ["Manager","10"]
]);

console.log("Before : ",company);

company.delete("Partner");

console.log("When Remove Partner :",company);
Before :  Map {
  'Tester' => '100',
  'Programmer' => '10000',
  'Client' => '100000',
  'Partner' => '5',
  'Manager' => '10' }
When Remove Partner : Map {
  'Tester' => '100',
  'Programmer' => '10000',
  'Client' => '100000',
  'Manager' => '10' }

map.size

size are return the value of number of existing elements in map.

//Create a map
let documents = new Map([
  ["File","100"],
  ["Books","10"],
  ["Images","50"],
]);

console.log("Size : ",documents.size);
Size :  3

map.clear()

This method are remove all element in existing map.

//Create a map
let documents = new Map([
  ["File","100"],
  ["Books","10"],
  ["Images","50"],
]);

console.log("Before : ",documents);

documents.clear(); //remove all element

console.log("After : ",documents);
Before :  Map { 'File' => '100', 'Books' => '10', 'Images' => '50' }
After :  Map {}

Iterating over a map

There are three ways to iterate map elements. By using key and value pair, by using key and by using values. Basically there are three method which are used to iterate map element. map.entries(), map.keys() and map.values().

//Create a map
let documents = new Map([
  ["File",100],
  ["Books",10],
  ["Images",50],
  ["EBook",30]
]);

console.log("Entries : ",documents.entries());
console.log("Keys : ",documents.keys());
console.log("Values : ",documents.values());
Entries :  MapIterator {
  [ 'File', 100 ],
  [ 'Books', 10 ],
  [ 'Images', 50 ],
  [ 'EBook', 30 ] }
Keys :  MapIterator { 'File', 'Books', 'Images', 'EBook' }
Values :  MapIterator { 100, 10, 50, 30 }

If you are understand the format of that returning value then you'll can get those element value by any loop. Let's seen an example to iterate map element by for-loop.

//Create a map
let documents = new Map([
  ["File",100],
  ["Books",10],
  ["Images",50],
  ["EBook",30]
]);
//Get key value pair
for(let [key,value] of documents.entries()){

  console.log("Key : ",key," Values :",value);
}
//Get all keys
for(let key of documents.keys()){
  console.log("Key : ",key);

}
//Get all keys values
for(let key of documents.values()){
  console.log("Value : ",key);
}
Key :  File  Values : 100
Key :  Books  Values : 10
Key :  Images  Values : 50
Key :  EBook  Values : 30
Key :  File
Key :  Books
Key :  Images
Key :  EBook
Value :  100
Value :  10
Value :  50
Value :  30

In case when you'll are try to retrieves map element by while loop. Then first you'll are need to convert map element into an array.Array.from() are used to convert MapIterator into an array. For example.

//Create a map
let map = new Map([
  ["File",100],
  ["Books",10],
  ["Images",50],
  ["EBook",30]
]);

var index=0;
var entries=Array.from(map.entries());
while(entries.length>index){
  console.log("Key : " ,entries[index][0],"  Value :",entries[index][1]);
  index++;
}

index=0;
var key=Array.from(map.keys());

while(key.length>index){
  console.log("Key  : ",key[index]);
  index++;
}

index=0;
var value=Array.from(map.values());
while(value.length>index){
  console.log("Value : " ,value[index]);
  index++;
}
Convert map iterators in form of arrays
Key :  File   Value : 100
Key :  Books   Value : 10
Key :  Images   Value : 50
Key :  EBook   Value : 30
Key  :  File
Key  :  Books
Key  :  Images
Key  :  EBook
Value :  100
Value :  10
Value :  50
Value :  30

WeakMap

Weakmap is type of map which contain key and value pairs. In this map, key can be form of an object or an arbitrary values.

new WeakMap()
new WeakMap([iterable])

Here iterable is form of an array or can be form of other, iterable objects.

//Create a empty weakmap
var weakMap = new WeakMap();

//Make objects
var first = {};
var second = function() {};

//make object as key
weakMap.set(first, 1000);
weakMap.set(second, 'Grow Level');

//Display map value by using key object
console.log(weakMap.get(first));
console.log(weakMap.get(second));
WeakMap Example
1000
Grow Level


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved