How to Transform Lists into Map Objects
It may happen that you need to convert an array of objects into map objects or vice versa. In this post, we will look at how to do that.
Transforming a List into a Map Object
Consider we have an array of game objects. Each game object has an id
and a name
.
const games = [
{id:1, name: 'Fornite'},
{id:2, name: 'RDR2'},
{id:3, name: 'Cyberpunk 2077'}
];
We want to convert the array of game data into an object mapping the id
to the name
of the game.
{
1: "Fornite",
2: "RDR2",
3: "Cyberpunk 2077"
}
forEach
One solution is to use the forEach
method to loop over the array and build the new mapping object. For each game element in the input array, we create a new property in the map
object. The property key is the id
of the game, and the property value is the name
of the game.
const map = {};
games.forEach(({id, name})=>{
map[id] = name;
});console.log(map);
//{1: "Fornite",
// 2: "RDR2",
// 3: "Cyberpunk 2077"}
reduce
We can implement a similar solution by using the reduce
array method.