How to convert Map keys to array?
JavascriptDictionaryEcmascript 6Javascript Problem Overview
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?
Javascript Solutions
Solution 1 - Javascript
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"]
Solution 2 - Javascript
You can use the spread operator to convert [Map.keys()][1] iterator in an Array.
let myMap = new Map().set('a', 1).set('b', 2).set(983, true)
let keys = [...myMap.keys()]
console.log(keys)
[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/keys "Map.keys()quot;"
Solution 3 - Javascript
I need something similiar with angular reactive form:
let myMap = new Map().set(0, {status: 'VALID'}).set(1, {status: 'INVALID'});
let mapToArray = Array.from(myMap.values());
let isValid = mapToArray.every(x => x.status === 'VALID');
Solution 4 - Javascript
OK, let's go a bit more comprehensive and start with what's Map for those who don't know this feature in JavaScript... MDN says:
> The Map object holds key-value pairs and remembers the original
> insertion order of the keys.
> Any value (both objects and primitive
> values) may be used as either a key or a value.
As you mentioned, you can easily create an instance of Map using new keyword... In your case:
let myMap = new Map().set('a', 1).set('b', 2);
So let's see...
The way you mentioned is an OK way to do it, but yes, there are more concise ways to do that...
Map has many methods which you can use, like set()
which you already used to assign the key values...
One of them is keys()
which returns all the keys...
In your case, it will return:
MapIterator {"a", "b"}
and you easily convert them to an Array using ES6 ways, like spread operator...
const b = [...myMap.keys()];
Solution 5 - Javascript
Not exactly best answer to question but this trick new Array(...someMap)
saved me couple of times when I need both key and value to generate needed array. For example when there is need to create react components from Map object based on both key and value values.
let map = new Map();
map.set("1", 1);
map.set("2", 2);
console.log(new Array(...map).map(pairs => pairs[0])); -> ["1", "2"]
Solution 6 - Javascript
myMap.map(([x,_]) => {x});
Above should also work