Lets say we have an object with some values
const objectWithSomeValues = {
numbers: 12345,
word: 'hello',
valueIDontWantToBeDeconstructed: [1,2,3,4,{}, null]
}
And somewhere else in the code I'm deconstructing this object
const someNewObject = {}
const { numbers, word } = objectWithSomeValues
/* and reassigning them to another */
someNewObject.numbers = numbers
someNewObject.word = word
Is there more elegant way to reassign those values to this object, maybe there is a one-liner that
List the valueIDontWantToBeDeconstructed and omit the others, and use rest syntax to collect those others into their own object.
const objectWithSomeValues = {
numbers: 12345,
word: 'hello',
valueIDontWantToBeDeconstructed: [1,2,3,4,{}, null]
};
const { valueIDontWantToBeDeconstructed, ...newObj } = objectWithSomeValues;
console.log(newObj);
Here you go:
const { numbers, word } = objectWithSomeValues;
const someNewObject = { numbers, word };
console.log(someNewObject); // { numbers: 12345, word: 'hello' }
Alternatively,
const someNewObject = {}
const { numbers, word } = objectWithSomeValues
Object.assign(someNewObject, {numbers, word});
console.log(someNewObject); // { numbers: 12345, word: 'hello' }