How to iterate Javascsript Map without forEach?

Viewed 2080

How to iterate over javascript Map without forEach (so I could break in the middle, or is there a way to break from forEach? Couldn't use object since the order is sometimes random on certain browser, where Map ordering is as defined.

let map = new Map();
map.set(1,'google.com');
// very long list
map.set(12312,/[^a-z]+/);

let match = 'nothing';
for(let z in map) { // doesn't work, but works for object
  if( foo.match(z) ) {
    match = map.get(z); // map[z]; on object
    break;
  }
}

the nearest thing i found is using .keys()

let iter = map.keys();
while(!iter.next().done) {
  if(foo.match(iter.value)) {
    match = map.get(iter.value);
    break
  }
}
1 Answers

Use for-of. Maps provide three iterators:

  1. For their entries, which are provided as [key, value] arrays. This is the default iterator for the map, and also available via the entries() method.

  2. For their keys: keys().

  3. For their values: values().

Here's an example looping through the entries, destructuring them into key and value constants:

for (const [key, value] of map) {
    // `key` is the key of the entry, `value` is the value
    if (/*...some condition...*/) {
        break;
    }
}

(You don't have to destructure, though, you could use for (const entry of map) and then use entry[0] for the key and entry[1] for the value.)

Or for looping keys:

for (const key of map.keys()) {
    // ...

Or for looping values:

for (const value of map.values()) {
    // ...

Applying the default iterator to your example code:

let map = new Map();
map.set(1,'google.com');
// very long list
map.set(12312,/[^a-z]+/);

let match = 'nothing';
for (const [key, value] of map) {
  if (foo.match(key)) {
    match = value;
    break;
  }
}
Related