0

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

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

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

4

2 回答 2

2

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

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

于 2022-01-08T00:16:48.433 回答
0

干得好:

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' }
于 2022-01-08T00:23:13.427 回答