I there an elegant way to re-assign deconstructed object values using ESNext

112 Views Asked by At

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

2

There are 2 best solutions below

0
On

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);

0
On

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