In this article we will learn how to add an element to a map.
It is very common to add an element to a map in JavaScript.
Problem
Now we have a problem, which is that we want to add an element to a map.
Now let's imagine we have a map like this:
// Map
['name', 'John'],
['age', 30],
And we want to add new element to this map, to become like this:
// (Added country)
['name', 'John'],
['age', 30],
['country', 'USA'],
How to solve this problem?
Fortunately, we have a built-in function that add elements to map called set
.
Add an elements to a map using set
We can use set
method to add an element to a map.
For Example
// Map
const map = new Map([
['name', 'John'],
['age', 30],
]);
// Before adding element
console.log(map);
// Add element
map.set('country', 'USA');
// After adding element
console.log(map);
Output
Map(2) { 'name' => 'John', 'age' => 30 }
Map(3) { 'name' => 'John', 'age' => 30, 'country' => 'USA' }
You should know you can chain multiple calls together.
// Map
const map = new Map([
['name', 'John'],
['age', 30],
]);
// Chaining elements
map.set('country', 'USA')
.set('degree', 'good')
.set('isMarried', false);
// Result:
console.log(map);
Output
Map(5) {
'name' => 'John',
'age' => 30,
'country' => 'USA',
'degree' => 'good',
'isMarried' => false
}
The keys in the map are unique, and this means that if you use more than one key with the same name, only one key will be added (last one)
// Map
const map = new Map([
['name', 'John'],
['age', 30],
]);
// Chaining elements
map.set('country', 'USA')
.set('country', 'UK')
.set('isMarried', false);
// After adding element
console.log(map);
Output
Map(4) {
'name' => 'John',
'age' => 30,
'country' => 'UK',
'isMarried' => false
}
As you noticed, the country field has been updated.
Thank you for reading
Thank you for reading my blog. 🚀 You can find more on my blog and connect on Twitter
Top comments (0)