Converting a Map to an Array of Objects in JavaScript


While working with Maps in JavaScript, you might need to convert it into an array of objects. Lets several approaches to do this:


Using Array.from() with a Map Function

One elegant method involves using Array.from() along with a map function. This allows you to iterate over the Map and transform its entries into a new array.

JavaScript
const myMap = new Map([
  ['key1', 'value1'],
  ['key2', 'value2'],
  ['key3', 'value3']
]);

const arrayOfObjects = Array.from(myMap, ([key, value]) => ({ key, value }));
console.log(arrayOfObjects);
// Output: [ { key: 'key1', value: 'value1' }, ... ]

This concise approach leverages the power of Array.from() to create a mapped array.

Using Array.map() Separately

Another method involves using Array.map() separately from Array.from(). Although functionally similar, this approach may be less performant due to the additional step.

JavaScript
const myMap = new Map([
  ['key1', 'value1'],
  ['key2', 'value2'],
  ['key3', 'value3']
]);

const arrayOfObjects = Array.from(myMap).map(([key, value]) => ({ key, value }));
console.log(arrayOfObjects);
// Output: [ { key: 'key1', value: 'value1' }, ... ]

Here, Array.from(myMap) creates an array of Map entries, and Array.map() transforms each entry into an object.

Using Map.forEach()

For those who prefer a direct iteration approach, using Map.forEach() can be a straightforward option. This method allows you to directly iterate over the Map entries and construct the array of objects.

JavaScript
const myMap = new Map([
  ['key1', 'value1'],
  ['key2', 'value2'],
  ['key3', 'value3']
]);

const arrayOfObjects = [];
myMap.forEach((value, key) => arrayOfObjects.push({ key, value }));
console.log(arrayOfObjects);
// Output: [ { key: 'key1', value: 'value1' }, ... ]

Using for…of Loop

A traditional looping approach involves utilizing the for…of loop to iterate over the Map entries. The for…of loop provides a readable way to iterate over Map entries and construct the desired array.

JavaScript
const myMap = new Map([
  ['key1', 'value1'],
  ['key2', 'value2'],
  ['key3', 'value3']
]);

const arrayOfObjects = [];
for (const [key, value] of myMap) {
  arrayOfObjects.push({ key, value });
}
console.log(arrayOfObjects);
// Output: [ { key: 'key1', value: 'value1' }, ... ]

Using Object Spread Syntax

Another approach involves using the object spread syntax, which can be particularly useful if your Map entries contain additional properties. Here, the object spread syntax is utilized to merge the Map key with the entry properties.

JavaScript
const myMap = new Map([
  ['key1', { value: 'value1', extra: 'info1' }],
  ['key2', { value: 'value2', extra: 'info2' }],
  ['key3', { value: 'value3', extra: 'info3' }]
]);

const arrayOfObjects = [...myMap.entries()].map(([key, entry]) => ({ key, ...entry }));
console.log(arrayOfObjects);
// Output: [ { key: 'key1', value: 'value1', extra: 'info1' }, ... ]

🧪Practice Coding Problem: Map and Modify to Array

In the spirit of Test Driven Development ( 😁), lets test our understanding by solving a problem.

Consider a scenario where you have a Map representing student grades. Each key is a student’s name, and the corresponding value is an array of their grades. Convert this Map into an array of objects where each object contains the student’s name and their average grade.

JavaScript
const gradesMap = new Map([
  ['Alice', [85, 90, 92]],
  ['Bob', [78, 89, 88]],
  ['Charlie', [92, 94, 89]]
]);

// Write a function 'convertGradesToArray' with:
//   - input :'gradesMap', and 
//   - output : an array of objects like:
//       - [{ name: 'Alice', averageGrade: 89 }, ... ]

function convertGradesToArray(gradesMap) {
  // > > > 👉 Write code here 👈 < < <
}

const result = convertGradesToArray(gradesMap);
console.log(result);
// Example output:
// [
//   { name: 'Alice', averageGrade: 89 },
//   { name: 'Bob', averageGrade: 85 },
//   { name: 'Charlie', averageGrade: 91 }
// ]
Please attempt before seeing the Answer:
JavaScript
function convertGradesToArray(gradesMap) {
  const resultArray = [];

  gradesMap.forEach((grades, name) => {
    const averageGrade = grades.reduce((sum, grade) => sum + grade, 0) / grades.length;
    resultArray.push({ name, averageGrade });
  });

  return resultArray;
}

This solution utilizes the forEach method to iterate over the Map entries, calculates the average grade for each student, and constructs an array of objects accordingly.


Hope you have sufficient ways to make an Array out of any Map in the Wrld!

Happy mapping and arraying! 🗺️🚀!

Scroll to Top