• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

202
Views
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.

about 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error