我有一种优雅的方法可以使用ESNext重新分配解构的对象值



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

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

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

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

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

你来了:

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' }

最新更新