Home > Back-end >  Improved way of Object destructing and assigning them to new state?
Improved way of Object destructing and assigning them to new state?

Time:12-26

I actually have below code

const someVariable = await promiseFunc()
someState.something1 = someVariable.something1
someState.something2 = someVariable.something2
someState.something3 = someVariable.something3
someState.something4 = someVariable.something4
someState.something5 = someVariable.something5
...
someState.something20 = someVariable.something20

It's not directly object desctruction, But I want to write in possibly one or two lines something like below . Is that possible ?

const someVariable = await promiseFunc()
someState { something1, something2, something3, something4 } = someVariable

Above syntax could be wrong, my only concern is to do 20 lines of code in 1 line

CodePudding user response:

If you want all the props of the someVariable

you can do

const someVariable = await promiseFunc()
const someState = Object.assign({}, someVariable);
// or
// const someState = {...someVariable};

if you want specifics you could do

const someVariable = await promiseFunc();
const {some1, some2, some5, some7} = someVariable;
const someState = { some1, some2, some5, some7};

CodePudding user response:

If someVariable is already an object then you could either make them equal to each other:

const someState = {...someVariable}; 

Then you could access the keys and values of someState just like someVariable.

Or you could follow the books by using Object.assign

const someState = Object.assign({}, someVariable);
  • Related