To convert a JavaScript Map object to an array, you can use the Array from() method or the spread operator …. Both methods will return an array of arrays, where each inner array contains the key-value pair of the original Map
object.
Convert map object to array in JavaScript example
Simple example code.
Using Array.from()
:
const myMap = new Map();
myMap.set('key1', 'value1');
myMap.set('key2', 'value2');
const myArray = Array.from(myMap);
console.log(myArray);
Using the spread operator ...
:
<!DOCTYPE html>
<html>
<body>
<script>
const myMap = new Map();
myMap.set('key1', 'value1');
myMap.set('key2', 'value2');
const myArray = [...myMap];
console.log(myArray);
</script>
</body>
</html>
Output:
Do comment if you have any doubts or suggestions on this Js conversion topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version