Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading