javascriptecmascript-6

Destructuring a Map


If I have an object in javascript like this:

let obj = {b: 3, c: 4, d: 6}

I can get the different parts out pretty easily if I destructure it, for example, I could just get c and d if I do:

let {c, d} = obj

Now this is great, but if I wanted to make a map:

let m = new Map()
m.set('b', 3).set('c', 4).set('d', 6)

I can get individual elements out with:

let c = m.get('c')
let d = m.get('d')

But is there any way to destructure an object like a map in the way that we did with a standard object. I find the syntax above so much simpler to use in many cases, that it actually serves as a pretty big disadvantage when using maps; despite the fact that you can get iterators by default and so on (list advantages here haha).


Solution

  • const m = new Map();
    m.set('b', 3)
     .set('c', 4)
     .set('d', 6);
     
    const [[,b], [,c], [,d]] = m;
    
    console.log(b, c, d);

    const [[,b], [,c], [,d]] = m;