add a key-value pair to a map in javascript

To add a key-value pair to a map in JavaScript, you can use the set() method of the Map object. Here's an example:

index.tsx
let myMap = new Map();

// Adding a key-value pair
myMap.set("key1", "value1");

// Adding another key-value pair
myMap.set("key2", "value2");
143 chars
8 lines

In the example above, we create a new Map object myMap. We then add a key-value pair "key1": "value1" using the set() method. We can add more key-value pairs by calling set() again with a different key and value.

Alternatively, you can also initialize a Map object with key-value pairs in a single line using the Map() constructor and passing an array of arrays where each sub-array contains a key-value pair. Here's an example:

index.tsx
let myMap = new Map([
  ["key1", "value1"],
  ["key2", "value2"]
]);
69 chars
5 lines

This creates a new Map object myMap with two key-value pairs "key1": "value1" and "key2": "value2".

gistlibby LogSnag