.map() a Javascript ES6 Map?

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) {
  console.log(entry);
}

Note, I’m using a lot of new stuff in that second example…
Array.from takes any iterable (any time you’d use [].slice.call( ), 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.

Leave a Comment