【问题标题】:I there an elegant way to re-assign deconstructed object values using ESNext [duplicate]我有一种优雅的方式来使用 ESNext [重复] 重新分配解构的对象值
【发布时间】:2022-01-08 00:15:17
【问题描述】:

假设我们有一个带有一些值的对象

const objectWithSomeValues = {
    numbers: 12345,
    word: 'hello',
    valueIDontWantToBeDeconstructed: [1,2,3,4,{}, null]
}

在代码的其他地方我正在解构这个对象

const someNewObject = {}
const { numbers, word } = objectWithSomeValues 
/* and reassigning them to another */
someNewObject.numbers = numbers
someNewObject.word = word

有没有更优雅的方式将这些值重新分配给这个对象,也许有一个单行

【问题讨论】:

    标签: javascript ecmascript-6 destructuring ecmascript-2021


    【解决方案1】:

    列出valueIDontWantToBeDeconstructed 并省略其他的,并使用rest 语法将这些其他的收集到自己的对象中。

    const objectWithSomeValues = {
        numbers: 12345,
        word: 'hello',
        valueIDontWantToBeDeconstructed: [1,2,3,4,{}, null]
    };
    const { valueIDontWantToBeDeconstructed, ...newObj } = objectWithSomeValues;
    console.log(newObj);

    【讨论】:

      【解决方案2】:

      给你:

      const { numbers, word } = objectWithSomeValues;
      
      const someNewObject = { numbers, word };
      
      console.log(someNewObject); // { numbers: 12345, word: 'hello' }
      

      或者,

      const someNewObject = {}
      const { numbers, word } = objectWithSomeValues
      Object.assign(someNewObject, {numbers, word});
      
      console.log(someNewObject); // { numbers: 12345, word: 'hello' }
      

      【讨论】:

        猜你喜欢
        • 2011-09-18
        • 2018-12-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-12
        • 1970-01-01
        • 2011-10-15
        • 2019-01-13
        相关资源
        最近更新 更多