0

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

Barmar
  • 669,327
  • 51
  • 454
  • 560
ColdHands
  • 928
  • 7
  • 28

2 Answers2

2

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);
CertainPerformance
  • 313,535
  • 40
  • 245
  • 254
0

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' }
steven7mwesigwa
  • 3,145
  • 2
  • 12
  • 24