First item from a Map on JavaScript ES2015

后端 未结 4 1058
眼角桃花
眼角桃花 2020-12-09 14:25

I have a Map like this:

const m = new Map();
m.set(\'key1\', {})
.
m.set(\'keyN\' {})

the Mapcan have 1 or many i

相关标签:
4条回答
  • 2020-12-09 15:14

    For the specific example you are wondering about, destructuring would be perfect.

    let m = new Map();
    m.set('key1', {});
    m.set('key2', {});
    
    let [[, obj]] = m;
    

    e.g.

    let [pair] = m;
    let [key, obj] = pair;
    

    is one option to destructure and then grab the value, but the easier option would be

    let [obj] = m.values();
    
    0 讨论(0)
  • 2020-12-09 15:17

    Use the Map.prototype.entries function, like this

    const m = new Map();
    m.set('key1', {})
    m.set('keyN', {})
    
    console.log(m.entries().next().value); // [ 'key1', {} ]


    If you want to get the first key, then use Map.prototype.keys, like this

    console.log(m.keys().next().value); // key1
    

    Similarly if you want to get the first value, then you can use Map.prototype.values, like this

    console.log(m.values().next().value); // {}
    

    The reason why we have to call next() on the returned values is that, all those functions return iterators. Read more about the iteration protocol here.

    0 讨论(0)
  • 2020-12-09 15:17

    Also, that is correct for both Set and Map: you can convert anything to Array and then get any element by its index. Something like this:

    const m = new Map();
    m.set('key1', {});
    m.set('key2', {});
    
    console.log(Array.from(m)[0]); // ['key1', {}]

    0 讨论(0)
  • 2020-12-09 15:22

    It could also done using spread feature at ES6 and next versions

    const m = new Map();
    m.set('key1', 1);
    m.set('key2', 2);
    
    console.log([...m][0]);    // ['key1', 1]                                                                     
    0 讨论(0)
提交回复
热议问题