Here are two ways to convert an Array to a Map in JavaScript.
- Using Array.map() method with Map() constructor
- Using Map set() and Array forEach() methods
Method 1: Array.map() method and Map()
Using the Array.prototype.map() method, you can convert an array of objects into an array of key-value pairs and then pass that to the Map constructor.
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.
Method 2: Map set() and Array forEach()
If you have an array of objects and you want to convert it into a map where each object becomes a key-value pair in the map, you can use the “Array.prototype.forEach()” method.
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' }
];
const userMap = new Map();
users.forEach(user => {
userMap.set(user.id, user);
});
console.log(userMap);
Output
Map(3) {
1 => { id: 1, name: 'Alice' },
2 => { id: 2, name: 'Bob' },
3 => { id: 3, name: 'Charlie' }
}
This is a clean and effective way to convert an array of objects into a map based on a specific property of the object.
That’s it!

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.