Set a ES6 Map from an array of objects in Typescript?

I have an array of objects like such…

const myObjects: MyObjects[] = [{id: 1, data: "blah"}, {id: 2, data: "foo"}, {id: 3, data: "bar"}];

I want to set this data into a Map based on id.

The way I have now is a forEach loop, but is there a simpler way or a method I am missing on the Map type ? I find myself doing this over and over again and thinking must be a simpler way.

i.e

const myMap = new Map<number, MyObject>();
myObjects.forEach(obj => {
  myMap.set(obj.id, obj);
});

I want to move them to a Map so they are easier to access by id versus iterating over the whole array.

Answer

Is there a simpler way or a method I am missing on the Map type?

“Simple” is a bit subjective. I usually use this approach because it fits in one line and because initializing a Map with some elements might be faster than initializing it and then adding elements.

const myObjects: { id: number; data: string; }[] = [{id: 1, data: "blah"}, {id: 2, data: "foo"}, {id: 3, data: "bar"}];
const myMap = new Map(myObjects.map(obj => [obj.id, obj]));

Explanation: The Map constructor takes an itrerable of iterables (in this case an array of arrays) as the first parameter. Each element in the main array is an entry in the map, with the key being the element’s first element and the value being the element’s second element.