Insert a key-value pair to a Map in JavaScript
This post will discuss how to insert a key-value pair to a Map in JavaScript.
There are several ways to add a key-value pair to a map in JavaScript, which is a common task involving associating a value with a unique identifier in the Map object. Here are some of the possible functions:
1. Using Map.prototype.set() function
This is the most standard and recommended way to add a key-value pair to a map in JavaScript. The Map.prototype.set() function sets the value for a key in a map, or updates it if it already exists. The set() function returns the map object itself, so it can be chained with multiple calls to this function or other functions. This works well for maps that are created using the Map() constructor. The following code illustrates this:
|
1 2 3 4 5 6 7 8 9 |
// Create a map with some key-value pairs const myMap = new Map([["a", 10], ["b", 20]]); // Add a new key-value pair and update an existing key-value pair // using the set() function myMap.set("c", 30).set("a", 15); // Print the updated map console.log(myMap); // Map(3) { 'a' => 15, 'b' => 20, 'c' => 30 } |
2. Using object literal syntax
This method works for maps that are created using the object. The object literal syntax creates an object with the specified properties and values. It can be used to create a map-like object, where the keys are strings or symbols and the values can be any type. However, this syntax does not create a true map object, and it does not support non-string keys. To add a key to an object literal, we can use the dot notation or the bracket notation. The following code illustrates this:
|
1 2 3 4 5 6 7 8 9 10 11 |
// Create an empty object const myMap = {}; // Add a key-value pair using dot notation myMap.a = 1; // Add another key-value pair using bracket notation myMap['b'] = 2; // Print the map object console.log(myMap); // { a: 1, b: 2 } |
3. Using spread syntax and Map constructor
We can use the Map() constructor with the spread syntax (…) to create a new map from an existing map and add a new key-value pair or update an existing one. This new map will contain all the key-value pairs from the original map and the new or updated one. The following code illustrates this:
|
1 2 3 4 5 6 7 8 9 |
// Create a map with some key-value pairs const myMap = new Map([["a", 10], ["b", 20]]); // Create a new map from the existing map and add few key-value pairs // using the spread syntax let newMap = new Map([...myMap, ["c", 30], ["d", 40]]); // Print the new map console.log(newMap); // Map(4) { 'a' => 10, 'b' => 20, 'c' => 30, 'd' => 40 } |
That’s all about inserting a key-value pair to a Map in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)