I have an array of uniform objects:
var objects = [{
id: 1,
name: one
}, {
id: 2,
name: two
}];
And I'm converting these to a Map by using the id
property of each object as Map keys:
var map = new Map();
objects.forEach(obj => map.set(obj.id, obj));
However, I'd like to do the conversion without:
- having to manually create a new map object myself, and
- having to manually iterate over the array and calling
set
myself
Additionally, I don't feel I should be making a utility function for this presumably native functionality.
Note: search queries for js array to map, or js convert array to map, or js map from array are all bloated with stone-age-era answers with
Object
, or solutions with a utility function. I'm looking for the native approach here.
I.e. I'm looking for the native JavaScript equivalent of mapping an array to a dictionary in C#, for example.
var map = list.ToDictionary(item => item.id);
This is so straightforward and convenient, yet interestingly enough, there is no Map.from
in JavaScript (even though there is an Array.from
).