Is there a way to destructure an object in JavaScript and alias the local destructured object?
Something like:
const env = {ENV_VAR_X, ENV_VAR_Y, ENV_VAR_Z} = process.env;
...and have env
become a local constant containing those selected environment variables. (I'm aware that my example doesn't work with babel)
{
ENV_VAR_X: "s867c7dsj4lal7",
ENV_VAR_Y: "hd73m20s-a=snf77f",
ENV_VAR_Z: "production"
}
Is there a way to achieve this aliasing?
On a side note, I'm using babel as my transpiler, then running the script with node so that I can leverage more ECMAScript 6 functionality.
According to my reading of the spec, this should be parseable, but it doesn't mean what you think. It would be parsed from right-to-left as
where the production
is defined, like all other assignments, as evaluating to the RHS, which is
process.env
.Therefore, your code is equivalent to
It's quite easy to validate this:
results in a new constant
a
being declared with the value1
, as you would expect. However, the value ofbar
is not an "alias to the deconstructed object", which would be{a: 1}
; it's the same asfoo
, which is{a: 1, b: 2}
.bar === foo
.What you are trying to do has been discussed many times here on SO and also in the ES discuss group. The bottom line is that there is no way to do this. All you can do is:
In other words, there is no way to "deconstruct from an object into an object", or "pick from an object into an object". You can only deconstruct from an object into variables.
You could fall back to the old-fashioned way:
which I know is horrible.
You could use the
pick
function from underscore or write your own, but that requires you to saywhich is only slightly less horrible.
We have "rest properties" and "spread properties" proposed for ES7, but they do not seem to help us here.
What we need is a new syntax for picking properties into another object. There have been various proposals made for this, none of which has gained much traction. One is the "extended dot notation", which allows a curly-bracketed construct to be put after a dot. In your case, you would write
You can find out more about this proposal here.