JavaScript Map values()
Syntax & Examples
Map.values() method
The values() method of the Map object in JavaScript returns a new Iterator object that contains the values for each element in the Map object in insertion order.
Syntax of Map.values()
The syntax of Map.values() method is:
values()This values() method of Map returns a new Iterator object that contains the values for each element in the Map object in insertion order.
Return Type
Map.values() returns value of type Iterator.
✐ Examples
1 Using values() to iterate over a Map
In JavaScript, we can use the values() method to get an iterator object and use it to iterate over the values of a Map.
For example,
- Create a new Map object
mapwith initial key-value pairs. - Use the
values()method to get an iterator objectiteratorfor themap. - Use a
for...ofloop to iterate over theiteratorand log each value to the console usingconsole.log().
JavaScript Program
const map = new Map([['a', 1], ['b', 2], ['c', 3]]);
const iterator = map.values();
for (const value of iterator) {
console.log(value);
}Output
1 2 3
2 Using values() to convert a Map to an array of values
In JavaScript, we can use the values() method to convert a Map object to an array of values.
For example,
- Create a new Map object
mapwith initial key-value pairs. - Use the
values()method to get an iterator objectiteratorfor themap. - Convert the
iteratorto an array using theArray.from()method and store it in the variablearrayOfValues. - Log
arrayOfValuesto the console usingconsole.log().
JavaScript Program
const map = new Map([['a', 1], ['b', 2], ['c', 3]]);
const iterator = map.values();
const arrayOfValues = Array.from(iterator);
console.log(arrayOfValues);Output
[ 1, 2, 3 ]
3 Using values() with a Map of objects
In JavaScript, we can use the values() method to iterate over a Map object containing objects as values.
For example,
- Create a new Map object
mapwith initial key-value pairs where values are objects. - Use the
values()method to get an iterator objectiteratorfor themap. - Use a
for...ofloop to iterate over theiteratorand log each value to the console usingconsole.log().
JavaScript Program
const map = new Map([
['person1', { name: 'John' }],
['person2', { name: 'Jane' }]
]);
const iterator = map.values();
for (const value of iterator) {
console.log(value);
}Output
{ name: 'John' }
{ name: 'Jane' }Summary
In this JavaScript tutorial, we learned about values() method of Map: the syntax and few working examples with output and detailed explanation for each example.