Lets say I have the following map:
let myMap = new Map().set('a', 1).set('b', 2);
And I want to obtain ['a', 'b']
based on the above. My current solution seems so long and horrible.
let myMap = new Map().set('a', 1).set('b', 2); let keys = []; for (let key of myMap) keys.push(key); console.log(keys);
There must be a better way, no?
We can get the keys from the map object using the built-in method map. keys(). To convert map keys to an array we have to first initialize a map object, followed by using the map. keys() method and then use the spread operator or array.
The map() method returns an entirely new array with transformed elements and the same amount of data. In the case of forEach() , even if it returns undefined , it will mutate the original array with the callback .
entries() Method in JavaScript The Map. entries() method in JavaScript is used for returning an iterator object which contains all the [key, value] pairs of each element of the map. It returns the [key, value] pairs of all the elements of a map in the order of their insertion.
How to convert Map keys to an array in JavaScript ? Given a Map and the task is to get the keys of the map into an array using JavaScript. Use keys () method on Map Object to get the keys of Map. Then use the array.from () method to convert map object to array.
Object[]objectArray=hashMap.entrySet().toArray(); System.out.println(Arrays.toString(objectArray)); Download Run Code Output: [RED=#FF0000, BLUE=#0000FF] 2. Convert map to array of keys We can get an array of keys of the map using Map.keySet()with Set.toArray(T[] a).
Call the keys () method on the Map to get an iterator object that contains all of the keys in the Map. Call the Array.from () method, passing it the iterator as a parameter. The Array.from method creates a new array from an iterable object. Copied! We used the Map.keys method to get an iterator object containing the keys of the Map.
We have seen that we can get an array of keys and values of the map using Map.keySet()and Map.values(), respectively. We can easily construct an array of key-value pairs from key[]and value[].
Map.keys()
returns a MapIterator
object which can be converted to Array
using Array.from
:
let keys = Array.from( myMap.keys() ); // ["a", "b"]
EDIT: you can also convert iterable object to array using spread syntax
let keys =[ ...myMap.keys() ]; // ["a", "b"]
You can use the spread operator to convert Map.keys() iterator in an Array.
let myMap = new Map().set('a', 1).set('b', 2).set(983, true) let keys = [...myMap.keys()] console.log(keys)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With