How to use the spread operator syntax In Javascript
The spread operator syntax can be used to destructure the map and then iterate through each element using the map() method with a callback function to push them into an array of objects.
Syntax:
[...mapName].map(([ObjectKeys...])=>{});
Example: The below code converts a map into an array of objects using the spread operator syntax.
const myMap = new Map();
myMap.set("Company", "w3wiki");
myMap.set("Cricketer", "Virat Kohli");
console.log("Map Elements: ", myMap);
const objectsArray =
[...myMap].map(([type, name]) => ({ type, name }));
console.log("Array of Objects: ", objectsArray);
Output
Map Elements: Map(2) { 'Company' => 'w3wiki', 'Cricketer' => 'Virat Kohli' } Array of Objects: [ { type: 'Company', name: 'w3wiki' }, { type: 'Cricketer', name: 'Virat Kohli' } ]
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