Clean way to keep original variable and destruction at the same time

别来无恙 提交于 2019-12-09 16:11:59

问题


Is there a cleaner way to do this (with anything that is at least an ES draft and has a babel plugin, i.e., ES6, ES7, etc.):

const { a, b } = result = doSomething();

Where I want to keep the overall result as one singular object, but also destructure it at the same time. It technically works, but result is implicitly declared (with an implicit var), while I'd really like it to also be a const.

I'm currently doing this:

const result = doSomething();
const { a, b } = result;

Which again works, but it's slightly on the verbose side, since I need to repeat this pattern dozens of times.

I'd ideally want something along the lines of:

const { a, b } = const result = doSomething();

But that is obviously an invalid syntax.


回答1:


One possible way:

const result = doSomething(), 
    { a, b } = result;

You still have to duplicate the name, though. const token isn't quite right-handy. )




回答2:


Idea 1

Create this helper function:

function use(input, callback) {
    callback(input, input);
}

and use it like:

use(doSomething(), (result, {a, b}) => {
    // Do something with result as a whole, or a and b as destructured properties.
});

For example:

use ({a: "Hello", b: "World", c: "!"}, (result, {a, b}) => {
  console.log(result);
  console.log(a);
  console.log(b);
});

// generates
// {a: "Hello", b: "World", c: "!"}
// Hello
// World

They're not const, but they're scoped, for better or worse!


Idea 2

Combine array and object deconstruction. Create this helper function:

const dup = input => [input, input];

And then deconstruct away like so:

const [result, {a, b}] = dup(doSomething());

Now, your result, a, and b are all consts.



来源:https://stackoverflow.com/questions/48039367/clean-way-to-keep-original-variable-and-destruction-at-the-same-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!