1
3829

JavaScript: How to Update Value to Map

Reading Time: 2 minutes

To update value to JavaScript Map object, we will utilise set method in JavaScript Map built-in object. We will illustrate updating of values with various datatype in this article.

set Method takes in a key and a value as the input parameter. If the key already exist, it will update the key with the new value.

DataType of value

When we add data or key-value pair to Map, we are able to initialise the Map values with any datatype. Hence, when we are updating, we will also need to consider the various datatype to update.

We will discuss the updating of the below 3 types.

  • Primitive (String, Number, Bigint, Boolean, Undefined, Symbol, null)
  • Array
  • Object

Primitive DataType

In the example below, we update the Map by directly placing the new value as the second parameter. If we only know the value during runtime, we can also place a variable that holds a primitive value.

const myMap = new Map([
  ['PrimitiveType', 'this is a string'],
]);

myMap.set('PrimitiveType', 'new string');

console.log(myMap.get('PrimitiveType'));   // "new string"

Array DataType

Here, let’s assume that we want to update the array elements.

There are 2 ways we can update.

  • Update Array reference: Use Spread Operator to expend the original array to a new array, then append the new element
  • Update Array directly: Get the original array reference via get() method, then push the value to the array
const myMap = new Map([
  ['ArrayType', [1,2,3,4,5]],
]);

// Update Array reference
const newArray = [...myMap.get('ArrayType'), 6];
myMap.set('ArrayType', newArray);
console.log(myMap.get('ArrayType'));   // [1,2,3,4,5,6]

// Update Array directly
myMap.get('ArrayType').push(7);
console.log(myMap.get('ArrayType'));   // [1,2,3,4,5,6,7]

Object DataType

Here, let’s assume that we want to update the object attribute.

There are 2 ways we can update.

  • Update Object reference: Use Spread Operator to expend the original array to a new array, then append the new element
  • Update Object directly: Get the original array reference via get() method, then push the value to the array
const myMap = new Map([
  ['ObjectType', { name: 'my-name' }],
]);

// Update Object reference
const newObject = { ...myMap.get('ObjectType'), age: 11 };
myMap.set('ObjectType', newObject);
console.log(myMap.get('ObjectType'));   // { age: 11, name: "my-name" }

// Update Object directly
myMap.get('ObjectType').height = 111;
console.log(myMap.get('ObjectType'));   // { age: 11, height: 111, name: "my-name" }

Conclusion

We have look into the methods to update a JavaScript Map base on its datatype. These methods will allow us to update Map. To update Map’s value that is array or object datatype, updating via the reference seems to be more human readable.

Show Comments

No Responses Yet

Leave a Reply