How to convert Map keys to array?

前端 未结 7 789
遥遥无期
遥遥无期 2020-12-12 10:32

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 abov

相关标签:
7条回答
  • 2020-12-12 11:13

    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)

    0 讨论(0)
  • 2020-12-12 11:15

    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"]
    
    0 讨论(0)
  • 2020-12-12 11:19

    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"]
    
    0 讨论(0)
  • 2020-12-12 11:19
    myMap.map(([x,_]) => {x});
    

    Above should also work

    0 讨论(0)
  • 2020-12-12 11:22

    Array.from(myMap.keys()) does not work in google application scripts.

    Trying to use it results in the error TypeError: Cannot find function from in object function Array() { [native code for Array.Array, arity=1] }.

    To get a list of keys in GAS do this:

    var keysList = Object.keys(myMap);
    
    0 讨论(0)
  • 2020-12-12 11:29

    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()];
    
    0 讨论(0)
提交回复
热议问题