Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 deep nested object destructuring

I have an object called this.props which contains

{  actions: Object,  dirty: false,  form: "Statement",  autofill: functon(),  **statement: Object** } 

statement contains

{  firstName: "John"  lastName: "Peter"  isConfirmed: true } 

I would like to extract statement object and the isConfirmed property in the same line using es6 destructuring

I've tried

const { statement: isConfirmed, isAdmin } = this.props 

which I get an error when I do let a = isConfirmed, b = statement

like image 836
chefcurry7 Avatar asked Nov 16 '16 01:11

chefcurry7


People also ask

Can you Destructure a nested object?

Destructuring nested objectsIf we need to access an employee's info we can destructure as many levels as it takes to get to our employee object's properties. const { engineers: { 1: { id, name, occupation, }, }, } = employees; Now we have access to all of the second employee object's properties.

How do you Destructure an object inside an array?

Destructuring in Arrays. 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. const [var1, var2, ...]

What is Destructure in ES6?

Destructuring means to break down a complex structure into simpler parts. With the syntax of destructuring, you can extract smaller fragments from objects and arrays. It can be used for assignments and declaration of a variable.

What is nested Destructuring?

JavaScript destructuring, nested and otherwise, is a nice shorthand to allow us to quickly define variables from values in a collection, object, or array. We can use it with rest syntax to assign remaining elements a variable. We can rename the elements that we pull out to a variable name of our choosing.


1 Answers

I would like to extract statement object and the isConfirmed property in the same line

const { statement: { isConfirmed }, statement } = this.props; 

That way you get both isConfirmed and the whole statement object.

References:

  • https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Nested_object_and_array_destructuring
like image 77
zerkms Avatar answered Sep 21 '22 23:09

zerkms