What is deconstruction?
Deconstruction is diametrically opposed to structured data. For example, instead of constructing a new object or array, it splits an existing object or array one by one to extract the data you need.
ES6 uses a new pattern to match the values you want to extract, and the solution assignment is to use this pattern. The pattern maps out the data structure you are deconstructing, and only those data that match the pattern are extracted.
The refactored data item is located to the right of the assignment operator =, can be any combination of arrays and objects, allowing arbitrary nesting. The number of variables used to assign values to these data is not limited.
Array Deconstruction
Array deconstruction uses an array as a data item, and you can extract the value from the array by using an array pattern (used to match the values you need from the array) to assign values to one or more variables.
The array pattern identifies which values you want to extract based on the location of the values. It must be able to accurately map the structure of the array so that each variable in the array pattern is assigned a value corresponding to the position in the deconstruction array.
Let me give you a few examples to help us understand:
Array Pattern Example
Assign all the values in the array to a single variable
Set
the array const avengers = [' Tony Stark ', ' Steve Rogers ', ' Natasha Romanoff '];
The array is reconstructed and assigned to the variable. The array pattern is on the left side of the assignment operator ' = ', and the array of the structure is on
//its right.
Const [Ironman, Cap, blackwidow] = Avengers;
Ironman = ' Tony Stark '
//cap = ' Steve Rogers '
//Blackwidow = ' Natasha romanoff '//
output Ironman:
Ironma N
Extract all values except the first one
Const AVENGERS = [' Tony Stark ', ' Steve Rogers ', ' Natasha Romanoff '];
We don't have to use Tony
const [, cap, blackwidow] = Avengers;
Ironman = error:undefined
/cap = ' Steve Rogers '
//Blackwidow = ' Natasha romanoff '/
output cap:
CA P
Extract all values except the second
Const AVENGERS = [' Tony Stark ', ' Steve Rogers ', ' Natasha Romanoff '];
Cap missing
const [Ironman,, Blackwidow] = Avengers;
Ironman = ' Tony Stark '
//cap = error:undefined
//Blackwidow = ' Natasha romanoff '//
output Blackwidow:
b Lackwidow;
Extract all values except the last one
Const AVENGERS = [' Tony Stark ', ' Steve Rogers ', ' Natasha Romanoff '];
Ironman vs Cap
const [Ironman, Cap] = Avengers;
Ironman = ' Tony Stark '
//cap = ' Steve Rogers '
//Blackwidow = error:undefined
//output Blackwidow:
I Ronman;
Nested arrays
This matching pattern also supports nested arrays, as long as the assignment operator = left side of the array pattern matches the array structure on the right. Again, = the variable on the left will be assigned = the position in the right array corresponds to the value. No matter how deep you nest, you can still deconstruct them.
To deconstruct a nested array
destructuring Nested Arrays
const AVENGERS = ['
Natasha Romanoff ',
[' Tony Stark ', ' James Rhodes '],
[' Steve Rogers ', ' Sam Wilson ']
];
Avengers and their are
const [Blackwidow, [Ironman, Warmachine], [cap, falcon]] = Avengers;
Blackwidow = ' Natasha Romanoff '
//Ironman = ' Tony Stark '//
Warmachine = ' James Rhodes '/
/cap = ' Steve Rogers '
//Falcon = ' Sam Wilson '
//Output warmachine:
warmachine;
Extract a value from a deeply nested array
Extract the Pepper Potts
const AVENGERS = [
' Natasha Romanoff ', [
[' Tony Stark ', ' Pepper Potts '], ' James Rhodes ' ],
[' Steve Rogers ', ' Sam Wilson ']
];
Destructure
Const [,//Skip ' Natasha romanoff ' [
[,//Skip ' Tony Stark '
Hera//Pepper assign value to variable ' Potts ' Hera 0/>]]] = Avengers;
Please note: You can also write
//const [, [[, Hera]]] = Avengers;
Output Hera:
Hera;
Hera = ' Pepper Potts '
Capture all remaining items using the rest operator
If you want to get a specific array of items and put the rest of the items in an array, then you can use the rest operator to deconstruct:
Fu
Const Avengers = [' Natasha romanoff ', ' Tony Stark ', ' Steve Rogers '] through rest operations;
const [Blackwidow, ... theothers] = Avengers;
Theothers;
Blackwidow = ' Natasha Romanoff '
//theothers = [' Tony Stark ', ' Steve Rogers ']
//output theothers:
theothers ;
Object Deconstruction
Object deconstruction is even more magical, especially when you need to take a value from a complex, deeply nested object. Again, object deconstruction and array deconstruction are the same rules (that is, an object pattern is created on the left side of the assignment operator, matching its variable position with the value position of the right object).
In the object deconstruction, you need to indicate the name of the property that needs to be fetched, and the name of the variable that will be assigned the value. As with array deconstruction, we need to first create an object pattern on the left side of the assignment operator to map the object that is being refactored.
Although in this case, we want to extract the value of the object attribute (e.g., we extracted from { prop: value
} value
). Accordingly, our object pattern must have a variable that is in the same position as the property value we are about to extract.
Simple example
Extract a Simple object property value
We can do this to assign the value of an object { ironMan: 'Tony Stark' }
's properties ironMan
'Tony Stark'
to a variable a
:
The property value of the Deconstruction object is assigned to a single variable ' a ':
const {IRONMAN:A} = {ironman: ' Tony Stark '};
Output A:
A; A = ' Tony Stark '
Extract multiple attribute values
As long as we extend the same pattern, we can extract multiple attribute values from an object, as follows:
Setup Our object
const Avengers = {
Ironman: ' Tony Stark ',
cap: ' Steve Rogers ',
blackwidow: ' Natasha Ro Manoff '
};
Destructure object to individual variables
const {
ironman:a,
cap:b,
blackwidow:c
} = Avenger s;
A = ' Tony Stark '
//b = ' Steve Rogers '
//c = ' Natasha Romanoff '//
Output A:
A;
See how this deconstruction pattern exactly matches the object being refactored.
Nested Object Deconstruction
Like a nested array, we can deconstruct a nested object, no matter how deep its hierarchy is.
Setup Our object
const Avengers = {
Blackwidow: ' Natasha romanoff ',
ironmancharacters: {couple
: {
ironman: ' Tony Stark ',
Hera: ' Pepper Potts ',
},
partner: {
warmachine: ' James Brodie '
}
} ,
capcharacters: {
cap: ' Steve Rogers ',
partner: {
Falcon: ' Sam Wilson '
}}}; Destructure object to individual variables
const {
blackwidow:a,
ironmancharacters: {
couple: {
ironman:b,
hera:c
},
partner: {
warmachine:d
}
},
capcharacters: {
Cap:e,
partner: {
falcon:f
}}}
= Avengers;
A = ' Natasha Romanoff '
//b = ' Tony Stark '
//c = ' Pepper Potts '//
d = ' James Brodie '//
e = ' Ste ve Rogers '
//F = ' Sam Wilson '
//Output A:
A;
To name a variable that is assigned a value
Of course, it's bad to set the variable name to something like A, B, C , and the variable name should be meaningful.
Long-Name
Setup Our object
const Avengers = {
Ironman: ' Tony Stark ',
cap: ' Steve Rogers ',
blackwidow: ' Natasha Ro Manoff '
};
Destructure object to individual variables with meaningful names
Const {
Ironman:ironman,
cap:cap,
Blackwidow:blackwidow
} = Avengers;
Blackwidow = ' Natasha Romanoff '
//Ironman = ' Tony Stark '/
/cap = ' Steve Rogers '/
/Output Blackwidow:
Blackwidow;
This approach is better than the a,b,c , but it can still be perfected. { ironMan: ironMan }
It looks a little ugly and not intuitive.
Grammar naming shortcuts
If you want to assign an object's attribute value to a variable that has the same name as the object's property name, then in the assignment pattern on the left, you simply write the attribute name, as follows:
Setup Our object
Const AVENGER = {
Ironman: ' Tony Stark '
};
Destructure object to individual variables with meaningful names
const {
Ironman //equivalent to ' Ironman: Ironman '
} = Avenger;
Ironman = ' Tony Stark '
/Output Ironman:
Ironman;
Because the property name of the object being reconstructed is the same as the variable name being assigned, we just need to list the name once.
Simple grammar
We'll just trim the previous code a little, and we can make them look more concise:
Setup Our object
const Avengers = {
Ironman: ' Tony Stark ',
cap: ' Steve Rogers ',
blackwidow: ' Natas Ha Romanoff '
};
Destructure object to individual variables with meaningful names
const {Ironman, cap, blackwidow} = Avengers;
//Output Ironman:
Ironman;
To extract a deeply nested property from an object
When we want to extract a deeply nested object attribute, things are even more interesting:
Setup Our object
const Avengers = {
Blackwidow: ' Natasha romanoff ',
ironmancharacters: {couple
: {
ironman: ' Tony Stark ',
Hera: ' Pepper Potts ',
},
partner: {
warmachine: ' James Brodie '
}
} ,
capcharacters: {
cap: ' Steve Rogers ',
partner: {
Falcon: ' Sam Wilson '
}}}; Destructure a deeply nested object
Const {ironmancharacters: {couple}} = Avengers;
Couple = {
// Ironman: ' Tony Stark ',
// Hera: ' Pepper Potts ',
//}
//Output couple:< C28/>couple;
Wait a minute, how did you read this piece of code? couple How is this variable defined?
By splitting this, we can see that the assignment operator = Left is a map of the destructor:
Const Avengers = {
ironmancharacters: {
couple: {
ironman: ' Tony Stark ',
Hera: ' Pepper Potts ',
}
}
};
const {
ironmancharacters: {
couple
}
} = avengers;
Output couple:
couple;
const { couple } = avengers;
There is no way to extract the value of couple by using it alone. Only the location and name of the object attribute to be extracted map out, the JS compiler can get the corresponding information, look down all the attributes of the object, and accurately extract the value we want.
Also note that couple uses a grammar shortcut to name the variable, which is actually:
const {
ironmancharacters: {
couple:couple
}
} = Avengers;
couple is defined as this, and its value is the value of the attribute named couple in the object Avengers .
Assign values to an object's properties
So far, we've been deconstructing the value of an object to assign a value to a single variable, and you can actually assign a value to another object's properties.
Const Avengers = {
Blackwidow: ' Natasha romanoff ',
ironmancharacters: {
couple: {
ironman: ' Tony Stark ' ,
Hera: ' Pepper Potts '
}
}
;
Const Ironmanproperties = {
family: {}
};
({
ironmancharacters: {
couple:ironManProperties.family
}
} = avengers);
ironmanproperties.family
//ironmanproperties.family = {
// Ironman: ' Tony Stark ',
// Hera : ' Pepper Potts '
//}
//Output ironmanproperties.family:
ironmanproperties.family;
Here we assign the ironManCharacters.couple
value to ironManProperties.family
This property, here are two points to explain:
1. The deconstruction assignment must be enclosed in parentheses
When we deconstruct an existing variable (such as the ironmanpropertiesin the example above), we must do so rather than declare a new variable.
2. Pattern still matches
{ ironManCharacters: { couple... } }
Matches the ironmancharacters in the object Avengers . So you can extract the value from the Avengers object as you wish ironManCharacters.couple
. But now, aftercouple a new object ironmanproperties and its attribute family, the object is actually assigned the property ironManProperties.family
.
Are you still confused when you try to explain the situation? Try the above code in the jsfiddle , and everything will be clear.
If you are not sure why you are doing this, please refer to the example in the next article. These examples will tell you why this pattern is used to deconstruct the JSON objects that the API calls, giving you a glimpse of the magic of deconstruction!
Default value
When deconstruction, you can also assign a default value to a variable:
Setup Our object
const Avengers = {
Ironman: ' Tony Stark ',
cap: ' Steve Rogers ',
blackwidow: ' Natasha Ro Manoff '
};
Destructure using defaults
const {Ironman, Cap, Blackwidow, thehulk= ' Bruce Banner '} = Avengers;
Ironman = ' Tony Stark '
//cap = ' Steve Rogers '
//Blackwidow = ' Natasha romanoff '/
/thehulk = ' Bruce Ban NER '
//Output Blackwidow:
Blackwidow;
To avoid these problems when deconstruction
no use of const, let, Var when deconstruction assignment
This is mentioned when we talk about the deconstruction of an object's properties, but there is a need to restate that and make a deep impression.
Cannot deconstruct a variable that has already been declared
That is, you can only declare variables while you are assigning values to them.
Setup Our object
const Avengers = {
Ironman: ' Tony Stark ',
cap: ' Steve Rogers ',
blackwidow: ' Natasha Ro Manoff ',
thehulk: ' Bruce Banner '
};
Valid destructuring
const {Ironman} = avengers;
Let {cap} = avengers;
var {blackwidow} = avengers;
Invalid destructuring let
thehulk;
{Thehulk} = avengers;
Error
//Output thehulk:
thehulk;
Why can't you deconstruct a variable that has already been declared? That's because then if you use curly braces { , JavaScript will think you're declaring a block.
The solution is to enclose the whole deconstruction assignment with a pair of parentheses .
How to deconstruct a declared variable
Setup Our object
const Avengers = {
Ironman: ' Tony Stark ',
cap: ' Steve Rogers ',
blackwidow: ' Natasha Ro Manoff ',
thehulk: ' Bruce Banner '
};
A valid Hulk let
thehulk;
({thehulk} = avengers);
Thehulk = ' Bruce Banner '
//Output thehulk:
thehulk;
Now we don't start with curly braces, so JS doesn't think we're declaring a block , so we can achieve the desired deconstruction result.
Returns a value that is being refactored directly
Without first declaring a variable to be returned, it returns a value that is being refactored directly, which is not expected. For example, in the following code, the entire Ironman object is returned, not the expected value, Tony Stark.
Note:this doesn ' t work!
function Gettonystark (Avengers) {return
{ironman: {realname}} = Avengers;
Return the Avengers object, not the Realname value
}
Const Avengers = {
Ironman: {
realname: ' Tony Star K '
}
};
Const Tonystark = Gettonystark (Avengers);
Tonystark = {// Ironman: {
// realname: ' Tony Stark '/
/ }
//};
Output Tonystark:
tonystark;
To extract a value from a Refactored object, you must first assign it to a variable, and then return the variable, as shown in the following code:
Note:this does work!
function Gettonystark (Avengers) {
Const {ironman: {realname}} = Avengers;
return realname;
}
Const Avengers = {
Ironman: {
realname: ' Tony Stark '
}
};
Const Tonystark = Gettonystark (Avengers);
Tonystark = ' Tony Stark '
/Output Tonystark:
tonystark;
The idea of dividing the assignment and return into two lines of code is annoying and ugly and unnecessary. Unfortunately, this is how JavaScript works----You must first assign the value of the deconstruction to a variable, and then return it, two steps must be done separately.
But, without saying that we just said to do it separately, did not say that we had to put in two lines of code, so writing a line like this would work as expected:
function Gettonystark (Avengers) {return
({ironman: {realname}} = avengers) && realname;
}
Const Avengers = {
Ironman: {
realname: ' Tony Stark '
}
};
Const Tonystark = Gettonystark (Avengers);
Tonystark = ' Tony Stark '
/Output Tonystark:
tonystark;
Due to the _short-circuit_
logical operators of JavaScript (&& | |) Returns the value of the second operand based on the value of the first operand, so this method of writing can achieve the desired result. Here, the first operand is the deconstruction assignment expression, which assigns the value to the realname. and Realname is the second operand, so its value is eventually returned.
This is not the best thing to do, but it can be achieved. While pursuing code brevity, be sure to be aware of the readability of your code.
Summarize
This article delves into the main principles of the construction of assignment values. Deconstruction can not only reduce the amount of code you have, but also fundamentally change the way you encode. The more you use, the more you will find that the way in which data and functions are modeled, these implementations are almost impossible in the past. I hope this article will help you to learn ES6.