Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 913
user2662833 Avatar asked Mar 30 '18 06:03

user2662833


People also ask

What does it mean to Destructure an object?

Destructuring is a JavaScript expression that allows us to extract data from arrays, objects, and maps and set them into new, distinct variables. Destructuring allows us to extract multiple properties, or items, from an array​ at a time.

What does it mean to Destructure an array?

Destructuring means to break down a complex structure into simpler parts. With the syntax of destructuring, you can extract smaller fragments from objects and arrays. It can be used for assignments and declaration of a variable.

What is Destructure?

To destroy the structure of something. To dismantle.


1 Answers

It's actually quite easy. In your code example,

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

you can just:

let a = [...m] // => [ [ 'b', 3 ], [ 'c', 4 ], [ 'd', 6 ] ]

or

let a = [...m.entries()] // same as above, more verbose

If you want to destruct individual values into b, c, d, we could:

let [b, c, d] = [...m.values()]

This would be the same as @Salih's answer, but a bit more readable.

like image 180
Marshal Avatar answered Oct 08 '22 04:10

Marshal