0

If you create a Map() is there any method whatsoever to iterate over it? I know Node 0.12 isn't out yet, but 0.11.x is well on it's way and I can't figure it out in the devel branch,

var m = new Map();
m.set('foo', 'bar');

Without knowing 'foo', is there anyway to discover that the key has been set? Is there a .keys() or anything on any object that will permit this or are we out of luck until v8 picks up more of ES6, and consequently the release of Node 0.14.

user157251
  • 64,489
  • 38
  • 208
  • 350

1 Answers1

0

Both Node.js 0.12 and iojs (since its initial release) implement iteration over Map and Set instances. With Map instances For example:

for (let entry of map) {
    // Do something with entry, which looks like [key, val]
}

or

map.forEach(function (val, key) {
    // Do something with key and val.
});

If you want to iterate over just the keys or just the values, then there are helper methods that return iterators called keys and values to do this.

qubyte
  • 16,350
  • 3
  • 26
  • 30
  • I assume this was accurate a few weeks ago, but an update is in order now that Node 0.12 is out. Even without the --harmony flag, Map.prototype.keys, Map.prototype.values, and Map.prototype.forEach are all implemented (same for Set, though note .keys() and .values() are synonymous in that case). – Semicolon Feb 15 '15 at 03:07