You can use the get()
method to get an element from a Map
object in JavaScript. The get()
method takes the element key as input and returns the value associated with the specified key, or undefined
if the key is not found in the Map
object.
const map = new Map()
map.set('name', 'John Doe')
map.set('age', 29)
map.set('job', 'UX Designer')
console.log(map.get('name')) // John Doe
console.log(map.get('age')) // 29
console.log(map.get('job')) // UX Designer
console.log(map.get('address')) // undefined
If the value associated with the specified key is an object, the get()
method will return a reference to that object. Any subsequent changes made to that object will also reflect inside the Map
object:
const product = { name: 'Milk', qty: 2 }
const prices = [2.99]
const items = new Map()
items.set('product', product)
items.set('prices', prices)
items.get('product').qty = 100
items.get('prices').push(4.55)
console.log(product)
// { name: 'Milk', qty: 100 }
console.log(prices)
// [ 2.99, 4.55 ]
Read this article to learn more about the Map
object and how 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.