I'd like to do something like this:
const vegetableColors = {corn: 'yellow', peas: 'green'};
const {*} = vegetableColors;
console.log(corn);// yellow
console.log(peas);// green
I can't seem to find or figure out how to do this but I really thought I had seen it done somewhere before! :P
NOTE: I'm using Babel with stage
set to 0
;
CONTEXT: I'm trying to be drier in JSX and not reference this.state
or this.props
everywhere. And also not have to keep adding properties to destructure if the data changes.
I think you're looking for the
with
statement, it does exactly what you are asking for:However, it is deprecated (in strict mode, which includes ES6 modules), for good reason.
You cannot in ES61. And that's a good thing. Be explicit about the variables you're introducing:
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 awith
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 :-)
I think yu're looking for:
Live on Babel's REPL
If Pointy's right that you're asking how to do this without knowing the names
corn
andpeas
, you can't with destructuring assignment.You can at global scope only, using a loop, but I'm sure you don't want to do this at global scope. Still, just in case:
(Throw
enumerable: true
on there if you want these pseudo-constants to be enumerable.)That works at global scope because
this
refers to the global object.