【问题标题】:ES6/Next: object destructuring with rest - groupingES6/Next: 对象解构与休息 - 分组
【发布时间】:2017-03-16 21:24:41
【问题描述】:

我有:

const props = {
  gallery: [],
  select: () => null,
  one: 1,
  two: 2,
}

我可以使用以下方法对其进行解构:

const {gallery, select, ...other} = props

我现在将有三个变量:

  • 图库 = []
  • 选择 = () => null
  • 其他 = {one: 1,two: 2}

是否可以分解为指定的分组?

类似这样的事情(这行不通,但我希望很清楚我正在尝试做什么):

const {{gallery, select}: specific, ...other} = props

所以我将有 2 个变量:

  • 具体 = {gallery: [], select: () => null}
  • 其他 = {one: 1,two: 2}

我可以在更高级别解决它并以这种方式构建道具:

const props = {
  specific: {
    gallery: [],
    select: () => null,
  },
  other: {
    one: 1,
    two: 2,
  }
}

但我只是想知道这是否可以通过解构实现。

【问题讨论】:

  • 可能可以使用spread properties 完成,但这在 ES6 中尚不可用
  • @SamiKuhmonen 它永远不会在 ES6 中可用。 ES6 规范已经完成。
  • @Gothdo 措辞含糊,我的意思是它在 ES 版本 6 中尚不可用,但可能会在以后的版本中。
  • “我可以用:” 不使用 ES6。或任何其他指定版本的 ES。 ...other (还)不是任何现有 ES 标准中的有效表达式。
  • 我更新了问题以提及 ES7 而不是 ES6,因为事实上,对象休息语法在 ES6 中不可用,并且建议用于 ES7。

标签: javascript ecmascript-6 destructuring ecmascript-next


【解决方案1】:

这个呢? 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 数据并且不直接访问道具的问题。

【讨论】:

    【解决方案2】:

    将语法(和可读性)扩展到您可以做到的极限:

    (对代码的解释在 cmets 中)

    const props = {
      gallery: [],
      select: () => null,
      one: 1,
      two: 2,
    }
    
    /** destructuring assignment **/
    const {
      gallery, //extract the gallery prop
      select, //extract the select prop
      specific: specific={gallery, select},
      // create `specific` setting gallery and select props through default value assignment 
      ...others // assign to others the rest of non extracted props properties
    } = props;
    
    console.log(specific);
    console.log(others);

    最后,我们在作用域中得到了一个gallery 和一个select 对象,但我们成功地使它们也成为了一个新的specific 对象的属性。

    使用警告:对象传播仍然是一个提案

    【讨论】:

    • 我对 stackoverflow 还是很陌生,所以我不太确定,我的假设可能有误,但看起来你已经使用了我的答案并改变了它......你不应该吗如果是这样的话,在我的评论中而不是发布新的答案?
    • @CésarLandesa 即使 sn-p 共享相同的样板,解决方案也不同,所以恕我直言没关系...
    • 但是解决方案是基于相同的想法来解决主要问题:在解构时使用默认值进行分组......然后你改进了这个概念,当然,但基于我的代码和 main主意。我想这是一个观点问题,但对我来说,这似乎是对我的想法的修改,而不是一个足够不同的解决方案。
    • @CésarLandesa 我认为解构赋值在它是单个表达式时很有用,这是我提出的与您提出的相比的核心
    猜你喜欢
    • 2020-02-18
    • 2017-07-24
    • 1970-01-01
    • 2018-08-30
    • 1970-01-01
    • 2017-11-02
    • 1970-01-01
    • 2018-04-12
    • 2020-08-28
    相关资源
    最近更新 更多