The set()
method is used to update or add an element's value in a Map
object. It takes two parameters: the key and the new value. If the Map
object already contains the key, the set()
method updates its value. Otherwise, it adds a new key-value pair to the Map
.
const map = new Map([
['name', 'Alex'],
['scores', [75, 87]],
['bio', { age: 27, country: 'Pakistan' }]
])
console.log(map)
// Map(3) {
// 'name' => 'Alex',
// 'scores' => [75, 87],
// 'bio' => { age: 27, country: 'Pakistan' }
// }
// Update name (STRING)
map.set('name', 'Alex Hales')
console.log(map.get('name')) // Alex Hales
// Update scores (ARRAY)
map.set('scores', [...map.get('scores'), 99])
console.log(map.get('scores')) // [75, 87, 99]
// Update bio (OBJECT)
map.set('bio', { ...map.get('bio'), job: 'Engineer' })
console.log(map.get('bio'))
// { age: 27, country: 'Pakistan', job: 'Engineer' }
In the above example, the name
, scores
, and bio
elements are updated with new values using the set()
method. The name
is updated with a string value, scores
with an array value by spreading the existing scores and adding a new score of 99, and bio
with an object value by spreading the existing bio object and adding a job
property.
You can also use the set()
method to add new elements to a Map
object:
const map = new Map([
['name', 'Alex'],
['scores', [75, 87]],
['bio', { age: 27, country: 'Pakistan' }]
])
map.set('email', 'alex@example.com')
console.log(map)
// Map(4) {
// 'name' => 'Alex',
// 'scores' => [75, 87],
// 'bio' => { age: 27, country: 'Pakistan' },
// 'email' => 'alex@example.com'
// }
In this case, the email
element is added to the Map
object with its corresponding value.
To learn more about the Map
object and how to utilize it to create collections of key-value pairs in JavaScript, you can refer to this article.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.