How to update a Value in a Map using JavaScript


Borislav Hadzhiev

Fri Oct 29 20212 min read


Photo by Luis Camacho

Update a Value in a Map using JavaScript #

Use the set() method to update a value in a Map, e.g. map.set('key', 'value'). The set() method adds or updates the element with the provided key and value and returns the Map object.

const map1 = new Map([ ['name', 'Tom'], ['numbers', [1, 2]], ['address', {country: 'Chile'}], ]); // ๐Ÿ‘‡๏ธ {'numbers' => [1, 2], 'name' => 'Tom', // 'address' => {country: 'Chile'}} console.log(map1); // โœ… Update STRING map1.set('name', 'Jim'); console.log(map1.get('name')); // ๐Ÿ‘‰๏ธ 'Jim' // โœ… Update ARRAY map1.set( 'numbers', [...map1.get('numbers'), 3], ); console.log(map1.get('numbers')); // ๐Ÿ‘‰๏ธ [1, 2, 3] // โœ… Update OBJECT map1.set( 'address', {...map1.get('address'), city: 'Santiago'}, ); // ๐Ÿ‘‡๏ธ๏ธ {country: 'Chile', city: 'Santiago'} console.log(map1.get('address'));

We used the Map.set() method to update a string, object and array values in a Map.

The set() method takes 2 parameters:

  1. The key of the element
  2. The value of th element
Note that the set() method also adds elements to a Map.

In the first example, we used the method to update a string value in the Map, nothing unexpected here.

Updating arrays and objects is a bit more tricky.

In our second example, we used the set() method to update an array.

To get access of the existing elements in an array, we used the Map.get() method, passing it the same key.

We used the spread syntax (...) to unpack the values of the array into a new array so we can add another element to it.

Our third example uses the same pattern to update an object. Again, we pass the same key to the set() and get() methods and add an additional key/value pair to the object using the spread operator.

You don't have to do this all in one step, you could call the get() method and store the value in a variable, which you can then manipulate, before updating it with the set() method.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee