Creating Variables For Destructured Objects In Addition To Their Properties
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 thi
Solution 1:
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 this looks very similar to, but is not the same as the following import
syntax you may have seen:
importReact, { Component } from'react'
Here, the variables in brackets are named exports, while the plain variable is the default export, which is entirely different from nested objects.
Solution 2:
You can destructure the state
to a variable as well:
const { state, state: { mode } } = { state: { mode: 'mode' } };
console.log(mode) // 'mode'console.log(state) // { mode: 'mode' }
Post a Comment for "Creating Variables For Destructured Objects In Addition To Their Properties"