Skip to content

.map() a Javascript ES6 Map?

How would you do this? Instinctively, I want to do:

var myMap = new Map([["thing1", 1], ["thing2", 2], ["thing3", 3]]);
// wishful, ignorant thinking
var newMap =, value) => value + 1); // Map { 'thing1' => 2, 'thing2' => 3, 'thing3' => 4 }

I’ve haven’t gleaned much from the documentation on the new iteration protocol.

I am aware of wu.js, but I’m running a Babel project and don’t want to include Traceur, which it seems like it currently depends on.

I also am a bit clueless as to how to extract how fitzgen/wu.js did it into my own project.

Would love a clear, concise explanation of what I’m missing here. Thanks!

Docs for ES6 Map, FYI


So .map itself only offers one value you care about… That said, there are a few ways of tackling this:

// instantiation
const myMap = new Map([
  [ "A", 1 ],
  [ "B", 2 ]
// what's built into Map for you
myMap.forEach( (val, key) => console.log(key, val) ); // "A 1", "B 2"
// what Array can do for you
Array.from( myMap ).map(([key, value]) => ({ key, value })); // [{key:"A", value: 1}, ... ]
// less awesome iteration
let entries = myMap.entries( );
for (let entry of entries) {

Note, I’m using a lot of new stuff in that second example… …Array.from takes any iterable (any time you’d use [] ), plus Sets and Maps) and turns it into an array… …Maps, when coerced into an array, turn into an array of arrays, where el[0] === key && el[1] === value; (basically, in the same format that I prefilled my example Map with, above).

I’m using destructuring of the array in the argument position of the lambda, to assign those array spots to values, before returning an object for each el.

If you’re using Babel, in production, you’re going to need to use Babel’s browser polyfill (which includes “core-js” and Facebook’s “regenerator”).
I’m quite certain it contains Array.from.