Destructuring a Map
Convert Map
to simple object
first
var obj = [...m.entries()].reduce( (acc, c) => (
acc[c[0]] = c[1],
acc), {}); //convert to object
Then you can destructure the same object
Demo
let m = new Map()
m.set('b', 3).set('c', 4).set('d', 6);
var obj = [...m.entries()].reduce( (acc, c) => (
acc[c[0]] = c[1],
acc), {}); //convert to object
//console.log(obj);
let { c, d } = obj;
console.log(c, d);
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;
You can't destructure Map directly, you will have to either convert to object first or do something exotic, like using Proxy to intercept get calls. Something like this with helper function:
function getFromMap (map) {
return new Proxy(map, {
get (obj, prop) {
return obj.get(prop)
}
})
}
let m = new Map()
m.set('b', 3).set('c', 4).set('d', 6)
let { b, d } = getFromMap(m)
console.log(b, d)
Thanks to @Felix Favour for comment. Using recent Object.fromEntries
function intermediate conversion map to object can be simplified:
let { b, d } = Object.fromEntries(m)