Search code examples
javascriptnode.jsdictionaryecmascript-6

Why can't I iterate the properties of my ES6 Map?


In the Node.js REPL:

> var map = new Map();
undefined
> map['foo'] = 'bar';
'bar'
> map['bar'] = 'baz';
'baz'
> map
Map { foo: 'bar', bar: 'baz' }
> map.forEach(console.log);
undefined

As you can see, the foo and bar keys are clearly defined within map, but when I try to iterate over them with Map.prototype.forEach, nothing happens - but according to MDN, it should. Note also that Map.prototype.forEach is defined, so it's not just that this method hasn't been implemented yet. I've also tried using a for ... of ... loop, with the same result - the code I provide to be run for each iteration doesn't actually run, even though it should.

I'm on Node.js v4.4.4. I searched the web for "javascript map isn't iterable node" and the like, with no luck.

What's going on here?


Solution

  • Not 100% positive, but I think you need to use map.set with Maps.

    var map = new Map();
    map.set('foo', 'bar');
    map.set('bar', 'baz');
    map.forEach(console.log);
    

    This will log out each of the items that you are looking for. Because the Map.prototype.forEach is looking for iterable properties, you need to use the set() function to set those iterable properties.