Skip to content

JavaScript Map keys to Array | Convert

  • by

Use the map key() method and Array from() method to convert Map keys to Array in JavaScript. Where Map.keys() returns a MapIterator object which can be converted to Array using Array.from:

Array.from( myMap.keys())

JavaScript Map keys Array

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script >
    var map = new Map();  
    map.set(1,"ABC");  
    map.set(2,"XYZ");  
    map.set([],"PQR");  

    let keys = Array.from(map.keys());
    console.log(keys);
  </script>
</body>
</html>

Output:

JavaScript Map keys to Array convert

You can also convert iterable object to array using spread syntax

let myMap = new Map().set('a', 1).set('b', 2);
let keys =[ ...myMap.keys() ];// ["a", "b"]

You could take Array.from and map the key/value pairs.

let map = new Map().set('a', 1).set('b', 2),
    array = Array.from(map, ([name, value]) => ({ name, value }));

console.log(array);

Output:

[
  {
    "name": "a",
    "value": 1
  },
  {
    "name": "b",
    "value": 2
  }
]

Do comment if you have any doubts or suggestions on this Js map topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *