Convert An Array Of Objects To A Map In JavaScript

To convert an array of objects to a Map in JavaScript –

  1. Use the Array.map() method to convert the array of objects to an array of key-value pairs and pass this array to the Map() constructor.
  2. You can also use a forEach loop to iterate over the array of objects and add each key-value pair to the Map.

Let’s look at both these methods  in detail.

Convert An Array Of Objects To A Map In JavaScript

convert an array of objects to a map in javascript

Array.map() Method

The Array.map() method is used to create a new array from the existing array and it does so by calling a callback function on each element of the original array. The map() method can be used with a forEach loop to convert an array of objects to a Map.

Consider the following example:

let arr =  [{ ‘name’: ‘John’, ‘age’: 30 },

           { ‘name’: ‘Peter’, ‘age’: 25 },

           { ‘name’: ‘Mary’, ‘age’: 28 }];         

const map = new Map(arr.map(item =>

          ([item.name, item.age])));

console.log(map); // Output: Map {‘John’ => 30, ‘Peter’ => 25, ‘Mary’ => 28}

In the above example, we have first converted the array of objects to an array of key-value pairs using the map() method and passed this array to the Map constructor. Notice that we have used the ES6 destructuring syntax to pass each object’s key and value as separate arguments to the map() callback function.

ForEach Loop

Another way to convert an array of objects to a Map is to use a forEach loop.

Consider the following example:

let arr =  [{ ‘name’: ‘John’, ‘age’: 30 },

           { ‘name’: ‘Peter’, ‘age’: 25 },

           { ‘name’: ‘Mary’, ‘age’: 28 }];         

const map = new Map();

arr.forEach(item => map.set(item.name, item.age));

console.log(map); // Output: Map {‘John’ => 30, ‘Peter’ => 25, ‘Mary’ => 28}

In the above example, we have first created an empty Map and then used the forEach loop to iterate over the array of objects. For each object in the array, we have added its key-value pairs to the Map using the set() method.

Notice that we had to create an additional variable here to store the Map.

Conclusion

In this article, we saw how to convert an array of objects to a Map in JavaScript. We looked at two methods to do so – using the Array.map() method and using a forEach loop.

Which method you choose depends on your specific requirements. If you need to perform any other operations on the array of objects before converting it to a Map, then using the map() method would be a good choice.

If you just need to convert the array of objects to a Map without any additional operations, then using a forEach loop would do the job just fine.

We hope you found this article helpful. Happy coding!

Leave a Reply