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
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.
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, ...]
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.
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With