Skip to content
Advertisement

.map() a Javascript ES6 Map?

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

JavaScript

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

Advertisement

Answer

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

JavaScript

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.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement