How to Convert an Array to Map in JavaScript

To convert an Array to a Map in JavaScript, you can use the “Map constructor”. The Map constructor takes an iterable (such as an array) of key-value pairs as its argument. You must transform your original array into an array of key-value pairs using the array.map() method.

Example

If you have an array of objects, you want to create a Map with the id property as the key and the entire object as the value.

const data = [
  { id: 1, name: 'Dhaval', age: 30 },
  { id: 2, name: 'Niva', age: 28 },
  { id: 3, name: 'Vidisha', age: 01 },
];

const dataMap = new Map(data.map(element => [element.id, element]));

console.log(dataMap);

Output

Map(3) {
  1 => { id: 1, name: 'Dhaval', age: 30 },
  2 => { id: 2, name: 'Niva', age: 28 },
  3 => { id: 3, name: 'Vidisha', age: 01 }
}

In this example, we used the array.map() method to create a new array of key-value pairs, where each pair is an array with two elements: the id property and the object itself. Then, we passed this new array to the Map constructor to create a Map.

Leave a Comment