JavaScript object destructuring and aliasing

后端 未结 1 721
慢半拍i
慢半拍i 2020-11-30 14:56

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         


        
相关标签:
1条回答
  • 2020-11-30 15:42

    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

    const env = ({ENV_VAR_X, ENV_VAR_Y, ENV_VAR_Z} = process.env);
    

    where the production

    ({ENV_VAR_X, ENV_VAR_Y, ENV_VAR_Z} = process.env)
    

    is defined, like all other assignments, as evaluating to the RHS, which is process.env.

    Therefore, your code is equivalent to

    const {ENV_VAR_X, ENV_VAR_Y, ENV_VAR_Z} = process.env;
    const env = process.env;
    

    It's quite easy to validate this:

    const foo = {a: 1, b: 2};
    const bar = {a} = foo;
    

    results in a new constant a being declared with the value 1, as you would expect. However, the value of bar is not an "alias to the deconstructed object", which would be {a: 1}; it's the same as foo, 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:

    const {ENV_VAR_X, ENV_VAR_Y, ENV_VAR_Z} = process.env;
    const env = {ENV_VAR_X, ENV_VAR_Y, ENV_VAR_Z};
    

    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:

    const env = {ENV_VAR_X: process.env.ENV_VAR_X, ...
    

    which I know is horrible.

    You could use the pick function from underscore or write your own, but that requires you to say

    const env = _.pick(process.env, 'ENV_VAR_X', "ENV_VAR_Y', 'ENV_VAR_Z');
    

    which 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

    const env = process.env.{ENV_VAR_X, ENV_VAR_Y, ENV_VAR_Z};
                           ^^
    

    You can find out more about this proposal here.

    0 讨论(0)
提交回复
热议问题