Monday, June 3, 2024
15
rated 0 times [  22] [ 7]  / answers: 1 / hits: 16340  / 8 Years ago, fri, january 20, 2017, 12:00:00

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).


More From » ecmascript-6

 Answers
99

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


[#59271] Wednesday, January 18, 2017, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brodyfrancisi

Total Points: 1
Total Questions: 102
Total Answers: 89

Location: Marshall Islands
Member since Mon, May 31, 2021
3 Years ago
brodyfrancisi questions
;