0

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.

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

FYI, the Map constructor shown here is documented at Relation with Array objects

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.