Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an array of objects with a unique id property to a Map

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?

like image 459
Baz Avatar asked Oct 24 '16 13:10

Baz


People also ask

How do I turn an array into a map?

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.

How do you map an array of objects?

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.

How do you change the properties of an array of objects?

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!

What is array prototype map () useful for?

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.


2 Answers

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.

like image 99
Ross Avatar answered Oct 06 '22 06:10

Ross


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)
}
like image 23
Michał Perłakowski Avatar answered Oct 06 '22 06:10

Michał Perłakowski