Javascript Map Object tutorials with examples

The map is the object used to hold key and value pairs. Key and values can contain either primitive types or custom data types. The reason for storing data in the map is key can be of any type.

Object Declaration syntax

Map objects can be created using the empty constructor or parameterized constructor.

new Map(parameters)
new Map()using Map() constructor, we can create an empty map.

Parameters in the constructor are optional which hold arrays of objects or iterable objects whose format should be key and value pairs

Object Declaration examples

The map can store all primitive types including NaN and Undefined in keys and values.

Empty Map Constructor
var mapVariable = new Map();
mapVariable.set('key1', 'value1')
mapVariable.set('key2','value2')
console.log(mapVariable.size) // outputs 2
console.log(mapVariable.get('key1'));    // returns value1 of key1

var x = new Map([['1', 'Emp1'], ['2', 'Emp2']);

console.log(x.size);
x.set('3', 'Emp3');
console.log(x.size);

var mapArray = new Map([['1', 'Emp1'], ['2', 'Emp2']]);
console.log(mapArray.size); // returns 2
mapArray.set('3', 'Emp3');
console.log(mapArray.size);  // returns 3
console.log(mapArray.get('1')); // returns Emp1
console.log(mapArray.set('1', 'kiran')); //setting Employee object
console.log(mapArray.get('1')); // returns Emp1
console.log(mapArray.size);  // returns 3  ```

_Map object_ extends from _Map.Prototype global object_. so all the methods in Map.prototype are available in the map object we will see important map methods with examples below.

## Object Properties

Map.size returns the size of the map object i.e Count of data(key+value)
**Frequently used Methods**
We will see the basic methods with examples and explanations.

## The clear() method

This method removes keys and values from a map Syntax and example.
 **Syntax is clear();**

```javascript
var clearMethodTest = new Map();
clearMethodTest.set(1,'test')
console.log(clearMethodTest.size); // returns 1
clearMethodTest.clear();
console.log(clearMethodTest.size); // returns 0

delete() method

This methods outputs true - if the key exists and removed key and corresponding value from the map false - if the key does not exist.

Syntax and Example

delete(key:object): Boolean
var mapArray = new Map([
  ["1", "Emp1"],
  ["2", "Emp2"],
]);
console.log(mapArray.size); // returns 2
mapArray.set("3", "Emp3");
console.log(mapArray.size); // returns 3 with initial size
console.log(mapArray.delete("1")); // returns true as key 1 exist and deleted
console.log(mapArray.size); // return 2  after deleted key
console.log(mapArray.get("1")); // returns undefined as there is no key exist

Entries() method

Entries method returns a new iterator object which contains key and value pair and map entries retrieved in insertion order

syntax & Examples

entries(): Iterator

return Iterator of arrays with key and values

var mapArray = new Map([
  ["1", "Emp1"],
  ["2", "Emp2"],
]);
console.log(mapArray.size); // returns 2
mapArray.set("3", "Emp3");
var iterator1 = mapArray.entries();
console.log(iterator1.next().value); // output: ["1", "Emp1"]
console.log(iterator1.next().value); // output: ["2", "Emp2"]
console.log(iterator1.next().value); // output: ["3", "Emp3"]
console.log(iterator1.next().value); // output: undefined

forEach Method

It is to iterate the objects of the map. Syntax and exam

myMap.forEach(callbackFunction{, optional arguments})

the callback function will be called on the key and value of each iterated arguments Arguments are optional

var mapArray = new Map([['1', 'Emp1'], ['2', 'Emp2']]);
console.log(mapArray.size); // returns 2
mapArray.set('3', 'Emp3');
mapArray.forEach(function (value, key) {
        console.log(key+':'+value);
}
output is
1:Emp1
2:Emp2
3:Emp3

get/set/has methods

get(key) method returns the value for a given key of a Map, undefined returned if the key does not exist. set(key, value) - save the value for the given key, if the key does not exist, create a new key and value. has(key)- return true if the key exists on the map, return false if a key does not exist on the map. Example

var mapArray = new Map([
  ["1", "Emp1"],
  ["2", "Emp2"],
]);
console.log(mapArray.size); // returns 2
mapArray.set("3", "Emp3");
console.log(mapArray.get("1")); // returns Emp1
console.log(mapArray.set("1", "New Emp")); // saves new value for key 1 and return new Map
console.log(mapArray.get("1")); // returns Emp1
console.log(mapArray.has("1")); // returns true
console.log(mapArray.has("15")); // returns false

keys() values() method

keys() returns iterator objects with keys values() returns iterator object with values

var mapArray = new Map([
  ["1", "Emp1"],
  ["2", "Emp2"],
]);
var mapArray = new Map([
  ["1", "Emp1"],
  ["2", "Emp2"],
]);
console.log(mapArray.size); // returns 2
mapArray.set("3", "Emp3");
var keys = mapArray.keys();
console.dir(keys.next()); // returns { value: '1', done: false }
console.dir(keys.next()); // returns { value: '2', done: false }
console.dir(keys.next()); // returns { value: '3', done: false }
console.dir(keys.next()); // returns { value: 'undefined', done: true }
var keys = mapArray.values();
console.dir(keys.next()); // returns { value: 'Emp1', done: false }
console.dir(keys.next()); // returns { value: 'Emp2', done: false }
console.dir(keys.next()); // returns { value: 'Emp3', done: false }
console.dir(keys.next()); // returns { value: 'undefined', done: true }

Next, we will see some of the example use cases of the Map object

How to convert Map to Object in javascript?

There are many ways to convert to ObjectOne easiest way is to use forEach iteration of the Map

const sourceMap = new Map();
sourceMap.set("booleanKey", true);
sourceMap.set("arrayKey", [{ a: 1 }, { b: 2 }, { c: 3 }]);
sourceMap.set("stringKey", "129");
const plainObject = {};
sourceMap.forEach(function (value, key) {
  plainObject[key] = sourceMap.get(key);
});
console.log(plainObject);

Clone of map object in javascript

Copy of a map can be done by the creation of a new map object with the parameter. Create a Map object like below

var newMap1 = new Map(original map)

Add data to map dynamically Data will be added to the map by calling the map constructor with an array/iterable of objects. you can add dynamically by using a set method of the object.

var dynamicMap = new Map();
dynamicMap.set("newkey", "newvalues");

Convert Map object to JSON object

use cases like map object to JSON or JSON to map object occurs during application development. Use JSON.stringfy() will convert to JSON object

mapArray.forEach(function (val, key) {
  var tempObj = {};
  tempObj[key] = val;
  jsonObj.push(tempObj);
});
console.log(jsonObj);
console.log(JSON.stringify(jsonObj));

That’s all my understanding of the javascript map object. I will document advanced Map examples in future articles.