How to use the Object.fromEntries() Method In Javascript
The Object.fromEntries() method transforms a list of key-value pairs into an object. We can use this method in combination with Object.entries() to create an array of objects from a map.
Example: The below example uses the Object.fromEntries() 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 mapObject = Object.fromEntries(myMap);
const objectsArray = Object.entries(mapObject).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