Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
171 views
Welcome To Ask or Share your Answers For Others

1 Answer

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"]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...