Creating variables for destructured objects in addition to their properties

  • A+

I have:

const { state: { mode } } = this  console.log(mode) //'mode' console.log(state) //undefined 

I want to declare the state variable as well.

Is there a way to destructure this without breaking it into two statements?

const { state } = this const { mode } = state 

Sure, just use a comma as if you were destructing another property of the parent object:

const obj = { state: { mode: 'str' }}; const { state: { mode }, state } = obj; console.log(mode); console.log(state);

Note that you can also do this with imports - that's why you see the following frequently:

import React, {Component} from 'react' 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: