How to use the forEach() method In Javascript
The forEach() method can be directly used to iterate the elements of the map and then push them into an empty array one by one with the help of the push() method.
Syntax:
mapName.forEach((objectKeys...)=>{arrayName.push()});
Example: The below code explains the use of the forEach() method to convert a map into an array of objects.
const myMap = new Map();
myMap.set("Company", "w3wiki");
myMap.set("Cricketer", "Virat Kohli");
console.log("Map Elements: ", myMap);
const objectsArray = [];
myMap.forEach
((name, type) => objectsArray.push({ name, type }));
console.log("Array of Objects: ", objectsArray);
Output
Map Elements: Map(2) { 'Company' => 'w3wiki', 'Cricketer' => 'Virat Kohli' } Array of Objects: [ { name: 'w3wiki', type: 'Company' }, { name: 'Virat Kohli', type: 'Cricketer' } ]
How to convert a map to array of objects in JavaScript?
A map in JavaScript is a set of unique key and value pairs that can hold multiple values with only a single occurrence. Sometimes, you may be required to convert a map into an array of objects that contains the key-value pairs of the map as the values of the object keys. Let us discuss some methods for converting a map into an array of objects in JavaScript.
Example:
Input Map: Map(2)
{
'Company' => 'w3wiki',
'Cricketer' => 'Virat Kohli'
}
Output Array:
[
{ type: 'Company', name: 'w3wiki' },
{ type: 'Cricketer', name: 'Virat Kohli' }
]
The below methods can be used to convert a map into an array of objects in JavaScript:
Table of Content
- Using the Array.from() method
- Using the spread operator syntax
- Using the Array.from() with Array.map() method
- Using the forEach() method
- Using the for of loop
- Using the Object.fromEntries() Method