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).
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.
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.
To destroy the structure of something. To dismantle.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With