JavaScript Map To Array


How to convert JavaScript Map to Array?

Let’s first create a map using JavaScript,

let jsMap = new Map();
jsMap.set('1', 'Mumbai'); 
jsMap.set('100', 'Delhi');
jsMap.set(102, 'Samba');

You can use keys, values and entries method on map object jsMap to get the key, values or key,value combined as an entry from the Map.

keys, values and entries methods returns iterables.

You can use Array.From to convert JavaScript Map to Array.

let jsMap = new Map();
jsMap.set('1', 'Mumbai'); 
jsMap.set('100', 'Delhi');
jsMap.set(102, 'Samba');

let list = Array.from(jsMap.entries());
console.log('Array list is ', list);
// "Array list is ", [["1", "Mumbai"], ["100", "Delhi"], [102, "Samba"]]

let list1 = Array.from(jsMap.keys());
console.log('Array list is ', list1);
// "Array list is ", ["1", "100", 102]

let list2 = Array.from(jsMap.values());
console.log('Array list is ', list2);
// "Array list is ", ["Mumbai", "Delhi", "Samba"]