How do I destructure all properties into the current scope/closure in ES2015?

I think you’re looking for the with statement, it does exactly what you are asking for:

const vegetableColors = {corn: 'yellow', peas: 'green'};
with (vegetableColors) {
    console.log(corn);// yellow
    console.log(peas);// green
}

However, it is deprecated (in strict mode, which includes ES6 modules), for good reason.

destructure all properties into the current scope

You cannot in ES61. And that’s a good thing. Be explicit about the variables you’re introducing:

const {corn, peas} = vegetableColors;

Alternatively, you can extend the global object with Object.assign(global, vegetableColors) to put them in the global scope, but really, that’s worse than a with statement.

1: … and while I don’t know whether there is a draft to allow such things in ES7, I can tell you that any proposal will be nuked by the TC 🙂

Leave a Comment