Here’s an example how you can convert Map to Array of object:
Code:
const convertMapToArray = (map) => {
return Array.from(map, ([name, value]) => {
return { name, value }
}); // convert using Array.from
}
const map = new Map();
map.set('key1', 1);
map.set('key2', 2);
const convertedArray = convertMapToArray(map); // function call
console.log(convertedArray);
Output:
[ { name: 'key1', value: 1 }, { name: 'key2', value: 2 } ]
Explanation:
Here, the Array.from method is used to convert a map to an array of arrays. So, if we use Array.from(map) then output will be [ [ name: ‘key1’, value: 1 ], [ name: ‘key2’, value: 2 ] ].
But here we want an array of objects so in the second argument we will pass below the callback function which converts array of arrays to array of objects.
([name, value]) => {
return { name, value }
}
Work with our skilled Javascript developers to accelerate your project and boost its performance.
Hire JavaScript Developers