Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 this without breaking it into two statements?

const { state } = this
const { mode } = state
like image 209
pailhead Avatar asked Apr 21 '18 20:04

pailhead


People also ask

How do we assign a default value to a Destructured parameter?

Default values in destructuring assignement only work if the variables either don't exist or their value is set to undefined . Any other value, including null , false and 0 , bypasses the default values in the destructuring statement. You can combine default values with renaming in the destructuring assignment.

How do you Destructure an array of objects?

To destructure an array in JavaScript, we use the square brackets [] to store the variable name which will be assigned to the name of the array storing the element.


2 Answers

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:

import React, { 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.

like image 140
CertainPerformance Avatar answered Sep 30 '22 02:09

CertainPerformance


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' }
like image 25
Ori Drori Avatar answered Sep 30 '22 03:09

Ori Drori