Iterating over a map
1 minute read
Iterate over map entries as key,value tuples.
const map = new Map([
["a", 1],
["b", 2],
["c", 3],
]);
for (const entry of map) {
console.log(entry);
}
[ "a", 1 ]
[ "b", 2 ]
[ "c", 3 ]
Iterate over the map, accessing the key and value parts as variables.
const map = new Map([["a", 1], ["b", 2], ["c", 3]]);
for (const [k, v] of map) {
console.log(`key: ${k} => value: ${v}`);
}
key: a => value: 1
key: b => value: 2
key: c => value: 3
Iterate over just keys.
const map = new Map([["a", 1], ["b", 2], ["c", 3]]);
for (const [key] of map) {
console.log(`key: ${key}`);
}
key: a
key: b
key: c
Iterate over just the values. Note that a placeholder is required for each key,
as designated by the underscore (_
).
const map = new Map([["a", 1], ["b", 2], ["c", 3]]);
for (const [_, value] of map) {
console.log(`value: ${value}`);
}
value: 1
value: 2
value: 3
Feedback
Was this page helpful?
Glad to hear it! Please tell us how we can improve.
Sorry to hear that. Please tell us how we can improve.