2
6

JavaScript: How to add data to JavaScript Map

Reading Time: < 1 minute

There are 2 methods to add data or key-value pair to JavaScript Map standard built-in object. Either during initialisation phase or runtime phase after the map is initialised. Let’s look into how it is done.

Phase to add data

  • Initialisation
  • Runtime

Before we go into the details, we have a more in-dept post here on how to create and use JavaScript Map for basic understanding.

Add data to Map on Initialisation

Below show the illustration on initialise map with data. It is simply having a 2-dimensional array to hold onto key-value pairs. We can initialise a Map with values of different datatype at the same time.

After initialisation, we will be able to get the results.

const ageMap = new Map([
  ['Person1', 11],
  ['Person2', 33],
  ['Person3', 44], 
  ['Person4', 66],
  [10000001, 11]
]);

console.log(ageMap.get('Person1'));   // 11
console.log(ageMap.get(10000001));    // 11
console.log(ageMap.get('10000001'));  // undefined

Add data to Map during Runtime

If there is a need to insert new key-value pair in the middle of the code, we can utilise set() to tell Map to include new key-value pairs into its dataset one at a time. In top of that, the key-value pairs can also be of different datatype.

const ageMap = new Map();

ageMap.set('Person1', 11);
ageMap.set(10000001, 11);

console.log(ageMap.get('Person1'));   // 11
console.log(ageMap.get(10000001));    // 11
console.log(ageMap.get('10000001'));  // undefined

Conclusion

To add data to any JavaScript Map, we can either perform it during the initialisation phase or use set() method to insert new key-value pairs.

For other examples, can refer to MDN documentation here.

Show Comments

No Responses Yet

Leave a Reply