How to Add a key/value Pair to Map in JavaScript ?
Last Updated :
10 Jun, 2024
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:
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);
OutputMap(3) { 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' }
Using map set() Method
In this method, we use the JavaScript map.set() method to insert the pair into the map.
Syntax:
myMap.set(key,value);
Example: In this example, we will insert some key-value pairs using map.set method.
JavaScript
const map1 = new Map();
// Insert pairs
map1.set('First Name','Jatin');
map1.set('Last Name','Sharma');
map1.set('website','GeeksforGeeks')
// Display output
console.log(map1)
OutputMap(3) {
'First Name' => 'Jatin',
'Last Name' => 'Sharma',
'website' => 'GeeksforGeeks'
}
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
Example: In this example, we will extend the map1 using spreate operator to iterate the map2 key-value pairs.
JavaScript
const map1 = new Map([
[1, 10],
[2, 21],
]);
const map2 = new Map([
["a", 100],
["b", 200],
]);
map1.set(...map2);
console.log(map1);
OutputMap(3) { 1 => 10, 2 => 21, [ 'a', 100 ] => [ 'b', 200 ] }
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.
Example: In this example, we will create an array map from given 2-d array.
JavaScript
// Given array
const arr = [
["a", 100],
["b", 200],
];
// Map object
let map1 = new Map();
// Iterate the array and insert pairs to map
arr.map(([key, value]) => map1.set(key, value));
// Display output
console.log(map1);
OutputMap(2) { 'a' => 100, 'b' => 200 }
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.
Example:
JavaScript
const obj = {
key1: 'value1',
key2: 'value2',
key3: 'value3'
};
const map1 = new Map([...Object.entries(obj)]);
// Display the map
console.log(map1);
OutputMap(3) { 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' }
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().
Example: In this example, we will use Array.prototype.forEach() to add key-value pairs to a Map.
JavaScript
// Given array of pairs
const pairs = [
["key1", "value1"],
["key2", "value2"],
["key3", "value3"]
];
// Create a new Map
const map1 = new Map();
// Use forEach to add each pair to the map
pairs.forEach(([key, value]) => {
map1.set(key, value);
});
// Display the map
console.log(map1);
OutputMap(3) { 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' }
Similar Reads
JavaScript Program to Update the Value for a Specific Key in Map
In this article, we will see different approaches to update the value for a specific key in Map in JavaScript. JavaScript Map is a collection of key-value pairs. We have different methods to access a specific key in JavaScript Map. Methods to update the value for a specific key in Map in JavaScriptT
3 min read
JavaScript Program to Split Map Keys and Values into Separate Arrays
In this article, we are going to learn about splitting map keys and values into separate arrays by using JavaScript. Splitting map keys and values into separate arrays refers to the process of taking a collection of key-value pairs stored in a map data structure and separating the keys and values in
5 min read
How to Change the Value of an Array Elements in JavaScript?
We can use the Square Bracket Notation to access the value at the given index and change the value by assigning a new value to it. Arrays in JavaScript are mutable, meaning you can modify their elements after they are created. We will explore all the approaches that can be used to access and change
3 min read
How to Merge Two Arrays Without Creating a New Array in JavaScript?
Given two arrays, the task is to merge both arrays to make a single array without creating a new array in JavaScript. It modifies one array in place to store the merged array elements.We can use the array push() method to insert array elements into another array using Spread Operator. This approach
2 min read
Convert 2D Array to Object using Map or Reduce in JavaScript
Converting a 2D array to an object is a common task in JavaScript development. This process involves transforming an array where each element represents a key-value pair into an object where keys are derived from one dimension of the array and values from another. Problem Description:Given a 2D arra
2 min read
JavaScript Program to Create an Array with a Specific Length and Pre-filled Values
In JavaScript, we can create an array with a specific length and pre-filled values using various approaches. This can be useful when we need to initialize an array with default or placeholder values before populating it with actual data.Table of ContentMethod 1: Using the Array() Constructor and fil
3 min read
JavaScript - Access Elements in JS Array
These are the following ways to Access Elements in an Array:1. Using Square Bracket NotationWe can access elements in an array by using their index, where the index starts from 0 for the first element. We can access using the bracket notation.JavaScriptconst a = [10, 20, 30, 40, 50]; const v = a[3];
2 min read
How to add Key-Value pair to a JavaScript Object?
A JavaScript object has a key-value pair, and it can be of variable length. We first need to declare an object and assign the values to that object for that there can be many methods.Below are the methods to add a key/value pair to a JavaScript object:Table of ContentUsing Dot NotationUsing Bracket
4 min read
How to get the Value by a Key in JavaScript Map?
JavaScript Map is a powerful data structure that provides a convenient way to store key-value pairs and retrieve values based on keys. This can be especially useful when we need to associate specific data with unique identifiers or keys.Different Approaches to Get the Value by a Key in JavaScript Ma
3 min read
How to store a key=> value array in JavaScript ?
In JavaScript, storing a key-value array means creating an object where each key is associated with a specific value. This allows you to store and retrieve data using named keys instead of numeric indices, enabling more intuitive access to the stored information.Here are some common approaches:Table
4 min read