You can use the set()
method to dynamically add an element to a Map
object in JavaScript. The set()
method adds or updates an element with the given key and value and returns the Map
object.
const map = new Map()
map.set('name', 'John Doe')
map.set('age', 27)
map.set('country', 'Pakistan')
console.log(map)
// Map(3) {
// 'name' => 'John Doe',
// 'age' => 27,
// 'country' => 'Pakistan'
// }
Since the set()
method returns back the same Map
object, you can chain multiple calls together, as shown below:
const map = new Map()
map.set('name', 'John Doe').set('age', 27).set('country', 'Pakistan')
console.log(map)
// Map(3) {
// 'name' => 'John Doe',
// 'age' => 27,
// 'country' => 'Pakistan'
// }
The Map
keys are unique. It means calling the set()
method more than once with the same key won't add multiple key-value pairs. Instead, the value is replaced with the newest value:
const map = new Map()
map.set('name', 'John')
map.set('name', 'John Doe')
console.log(map)
// Map(1) {
// 'name' => 'John Doe'
// }
The Map
object allows us to store object literals, arrays, and even functions as a key or value:
const menu = {
sandwich: '🥪',
cookie: '🍪',
popcorn: '🍿'
}
const pizza = () => '🍕'
const foods = new Map()
foods.set(menu, 5.9)
foods.set(pizza, 'What is Pizza?')
console.log(foods.get(menu)) // 5.9
console.log(foods.get(pizza)) // What is Pizza?
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.