12

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:

  1. having to manually create a new map object myself, and
  2. 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).

1 Answer 1

32

I did my research while writing up the question, and I feel I should leave the solution here, as its possible practical applications are many.


I'm looking for the native JavaScript equivalent of mapping an array to a dictionary in C#

Considering a Map can be constructed with an iterable of 2-element arrays, where the first element of each inner array is used as the key, and the second element is used as a value, I believe this is the native JS equivalent, also the shortest:

new Map(objects.map(obj => [obj.id, obj]));

Live demo

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

1 Comment

Make sure to polyfill Map if you target non-supported browsers. Check this table for browser support. It's already used in core-js, which is commonly used along with Babel.

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.