I have an array of objects, where each object has a unique member called id
. How do I create a Map where the id
if the Map's key?
To convert an array of objects to a map, we can use the Array map() method to create an array of key-value pairs, and then pass the resulting array to a Map() constructor to create a Map object.
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.
To update an object's property in an array of objects, use the map() method to iterate over the array. On each iteration, check if the current object is the one to be updated. If it is, modify the object and return the result, otherwise return the object as is. Copied!
Array.prototype.map() The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
You want to reduce your array into a map:
const arr = [{id:1},{id:2},{id:2}];
const map = arr.reduce((acc, item) => acc.set(item.id, item), new Map());
console.log(map.get(1));
Here is a JSPref against using map
and forEach
.
In Chrome v53 reduce
is fastest, then forEach
with map
being the slowest.
You can use Array.prototype.map()
to map the array elements to [element.id, element]
pairs and then pass the resulting array to the Map
constructor.
const arr = [{id: 1, a: true, b: false}, {id: 2, a: false, b: true}]
const map = new Map(arr.map(element => [element.id, element]))
// Check if map looks OK
for (const [key, value] of map) {
console.log(key, value)
}
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