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.