Map constructor

This method uses the map Constructor function to create the required JavaScript map.

Syntax:

const myMap  = new Map()        
// or
const myMap = new Map(iterable) // Iterable e.g., 2-d array

Example: In this example, we will create a Map from the 2-d array using a map constructor

Javascript
const map1 = new Map([
    ["key1", "value1"],
    ["key2", "value2"],
    ["key3", "value3"],
]);

// Display the map
console.log(map1);

Output
Map(3) { 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' }

How to Add a key/value Pair to Map in JavaScript ?

This article will demonstrate how we can add a key-value pair in the JavaScript map. JavaScript Map is a collection of key-value pairs in the same sequence they are inserted. These key values can be of primitive type or the JavaScript object.

All methods to add key-value pairs to the JavaScript Map:

Table of Content

  • Map constructor
  • Using map set() Method
  • Using Map object and spread operator
  • Using Array map() Method
  • Using Object.entries() and Spread Operator
  • Using Array.prototype.forEach()

Similar Reads

Map constructor

This method uses the map Constructor function to create the required JavaScript map....

Using map set() Method

In this method, we use the JavaScript map.set() method to insert the pair into the map....

Using Map object and spread operator

This method demonstrate how we can extend a given map or insert the pairs from a new map using the spread operator...

Using Array map() Method

In this method we will create a JavaScript map object from a 2 dimensional array without using the map constructor by using array.map() method....

Using Object.entries() and Spread Operator

This method converts an object into a Map using ‘Object.entries()’ which returns an array of a given object’s own enumerable string-keyed property [key, value] pairs....

Using Array.prototype.forEach()

This method demonstrates how to add key-value pairs to a Map by iterating over an array of pairs using Array.prototype.forEach()....

Contact Us