0

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

2 Answers2

2

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};
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
2

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);
Dennis Quan
  • 149
  • 1
  • 5