I have an array of objects, where each object has a unique member called id
. How do I create a Map where the id
if the Map's key?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
You can use
Array.prototype.map()
to map the array elements to[element.id, element]
pairs and then pass the resulting array to theMap
constructor.You could map a new array in the needed format for the Map.
Or iterate and add the new item to a certain key
You want to reduce your array into a map:
Here is a JSPref against using
map
andforEach
.In Chrome v53
reduce
is fastest, thenforEach
withmap
being the slowest.