javascript - ES6/下一个 : object destructuring with rest - grouping

标签 javascript ecmascript-6 destructuring ecmascript-next

我有:

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/

相关文章:

javascript - React State Hook如何从ES6 Destructuring Assignment中获取状态变量名

php - 在不刷新页面的情况下单击链接运行 PHP 脚本

javascript - Highcharts - 从数组填充数据

javascript - 在分派(dispatch)之间检测到状态突变,但我没有改变状态

javascript - ES6 数组解构并分配给没有函数的对象

macros - database_column_names 的 clojure-variable-names

javascript - 如何使用 JAVASCRIPT 在每个 HTML 表格行中添加按钮

javascript - 通过括号表示法访问外部作用域的变量

reactjs - React-native:将动画值保留在状态中还是作为类属性?

javascript - 对象破坏是通过引用工作还是克隆对象