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:
set
myselfAdditionally, 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
).
The syntax for the map() method is as follows: arr. map(function(element, index, array){ }, this); The callback function() is called on each array element, and the map() method always passes the current element , the index of the current element, and the whole array object to it.
Answer: Use the find() Method You can simply use the find() method to find an object by a property value in an array of objects in JavaScript. The find() method returns the first element in the given array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.
map() method. .map() creates an array from calling a specific function on each item in the parent array. .map() is a non-mutating method that creates a new array, as opposed to mutating methods, which only make changes to the calling array. This method can have many uses when working with arrays.
To convert an array's values to object keys:Use the reduce() method to iterate over the array. On each iteration, assign the array element as a key in the accumulator object. The reduce method will construct an object from the array's values.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With