Update an element in a Map using JavaScript

You can use the set() method to update an element value in a Map object. The set() method adds or updates an element with the specified key and value and returns the Map object.

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' }

The set() method takes two parameters: the element key and the value. If the Map object already contains the key, it updates the value. Otherwise, it adds a key-value pair to the Map object.

You can also use the set() method to add 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'
// }

Read this article to learn more about the Map object and how to use it to create collections of key-value pairs in JavaScript.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.