我有:
const props = {
gallery: [],
select: () => null,
one: 1,
two: 2,
}
我可以用以下方式解构它:
const {gallery, select, ...other} = props
我现在将有三个变量:
- 图库 =
[]
- 选择 =
() => null
- other =
{one: 1,two: 2}
是否可以解构为指定的分组?
类似这样的事情(这是行不通的,但我希望清楚地看到我正在尝试做什么):
const {{gallery, select}: specific, ...other} = props
所以我将有 2 个变量:
- 具体 =
{gallery: [], select: () => null}
- other =
{one: 1,two: 2}
我可以在更高层次上解决它并以这种方式构建 Prop :
const props = {
specific: {
gallery: [],
select: () => null,
},
other: {
one: 1,
two: 2,
}
}
但我只是想知道这是否可以通过解构实现。
最佳答案
这个呢? others
还包含 specific
数据,我必须首先访问 props
(也许这可以改进),但我认为它基本上分组在解构时。它之所以有效,是因为您可以在属性不存在时分配默认值:
const props = {
gallery: [],
select: () => null,
one: 1,
two: 2,
}
const {gallery : gal, select : sel} = props;
const {specific: specific={gallery: gal, select: sel}, ...others} = props;
console.log(specific);
console.log(others);
编辑
你也可以改变
const {gallery : gal, select : sel} = props;
const {specific: specific={gallery: gal, select: sel}, ...others} = props;
与:
const {specific: specific={gallery: props.gallery, select: props.select}, ...others} = props;
如果你想要它在一行中。
此外,maioman's answer解决了我在 others
中提到的包含 specific
数据并且不直接访问 props 的问题。
关于javascript - ES6/下一个 : object destructuring with rest - grouping,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40399034/