This is the 8th day of my participation in Gwen Challenge

Object to deconstruct

New in ES6, multiple assignment operations can be performed simultaneously. MDN

Extract an attribute of an object into a variable.

Basic usage

const herb = {
    name: "herb".age: 18
}
let herbName = herb.name,
    herbAge = herb.age;
Copy the code

The previous method was too cumbersome.

let { name: herbName, age: herbAge } = herb;
Copy the code

Now in this way, the two pieces of code are equivalent.

Let {attribute name: variable name} = deconstruct the object

let { name, age } = herb;
// equivalent to: let name = herb.name; let age = herb.age;
Copy the code

= Put the object to be deconstructed on the right, which can be an expression that returns an object.

The {} parentheses to the left of = indicate which attribute names are to be deconstructed from the object, followed by the variable name, that is, where the corresponding attribute value is stored. If no: indicates that the attribute name is the same as the variable name.

let name, age;
( { name, age } = herb );
Copy the code

If you assign a value to a previously declared variable, the assignment expression must be enclosed in a pair of parentheses.

Define default values while deconstructing assignments

const herb = {
    name: "herb".age: null
}
let { name: herbName = "person", age = 20, sex = "Male" } = herb;

// name: "herb"
// age: undefined
// sex: "male"
Copy the code

Let {attribute name: variable name = default value} = Destruct object

If herb.sex does not exist, the default values are used, or the attribute values in the object are undefiend, the default values are also used.

The above code, which is equivalent to: first defines herbName, age, sex three variables, and then from object: read out in front of the property names assigned to these variables, if the attribute value is undefined, use the default values.

You can deconstruct properties on the prototype chain

class Animal {
    constructor(type, age, sex) {
        this.type = type;
        this.age = age;
        this.sex = sex;
    }
    call() {
        console.log("aaaa"); }}class Person extends Animal {
    constructor(type, age, sex, name) {
        super(type, age, sex);
        this.name = name; }}const herb = new Person("Human".18."Male"."herb");
Copy the code
let { name, age, sex, call } = herb;
// name: "herb"
// age: 18
// sex: "male"
// call: call() { console.log("aaaa") }
Copy the code

Properties on the prototype chain can also be deconstructed, whether traversable or not.

Since objects are accessible as long as they are on the prototype chain, they can also be assigned to new variables.

Use computed property names

const arr = [1.2.3.4];
let{[Symbol.iterator]:it } = arr;
// it: function
let key = "z";
let { [key]: foo } = { z: "bar" };
// foo: "bar"
Copy the code

Can be used in combination.

Implicitly convert the object to be deconstructed into an object

let { length } = "1234";
// length: 4
let { constructor:c } = 100;
// c == Number
Copy the code

The original values are converted to objects for deconstruction.

let { a } = null
let { b } = undefined
Copy the code

Null and undefined cannot be deconstructed, otherwise an error will be reported.

Nested deconstruction

const user = {
    name: "herb".age: 19.sex: "Male".address: {
        province: "Zhejiang".city: "Jiaxing"}}Copy the code
let { address } = user;
// address
/ / {
// province: "province ",
// City: "jiaxing"
// }
Copy the code

Deconstructed as an object.

let { address: { province, city } } = user;
// address does not exist
// province: "province"
// City: "jiaxing"
Copy the code

Let creates the province and city variables. It does not create address, but finds address from user and finds province and city from address.

let { province, city } = user.address;
Copy the code

Instead of nested destructions inside {}, you can write the structure directly to the right of =.

let { hobby: { food, sport } } = user;
// Uncaught TypeError: Cannot read property 'food' of undefined
Copy the code

Note: You cannot use nested structures if the outer attributes are not defined. User doesn’t have a Hobby property, and nested destructuring it is bound to go wrong.

An array of deconstruction

const arr =  [0.1.2.3.4];
Copy the code
const { 0: a, 4: e } = arr;
// a: 0
// e: 4
Copy the code

An array is essentially an object, so it can be deconstructed as an object.

const [a, , , , e] = arr;
// a: 0
// e: 4
Copy the code

Arrays also have their own way of deconstructing, denoted by [], where the order of variables represents the order of elements in arR. We omit the index, which is a simplified version of the last one, but to get two indices that are not contiguous, we’re going to say how many elements in the array we’re going to skip.

const arr =  [0.1[2.3.4]].let [, , [c, d]] = arr;
// c: 2
// d: 3
let [two, three] = arr[2];
// two: 2
// three: 3
Copy the code

You can also nest destructions.

The remaining parameters

const user = {
    name: "herb".age: 19.sex: "Male".address: {
        province: "Zhejiang".city: "Jiaxing"}}Copy the code
let{ name, ... prop } = user;// name: "herb"
// prop: {
// address: {type: "province ", city:" jiaxing "}
// age: 19
// sex: "male"
// }
Copy the code

. The rest of the prop argument collects all undeconstructed properties and encapsulates them into new objects.

It is very convenient to exclude certain attributes of an object.

let{... prop1, age, ... prop2 } = user;// Uncaught SyntaxError: Rest element must be last element
Copy the code

Note: Remaining arguments can only appear in the last digit.

Switching variable

let a = 1;
let b = 3;

[a, b] = [b, a];
Copy the code

Assemble a and B into an array and swap variables by deconstructing them.

a = a ^ b;
b = a ^ b;
a = a ^ b;
Copy the code

You can also swap places this way, but only for the number type.

Complex deconstruction

const article = {
    title: "Article title".content: "Article content".comments: [{
        content: "Comments 1".user: {
            id: 1.name: "Username 1"}}, {content: "Comments 2".user: {
            id: 2.name: "Username 2"}}}]// Deconstruct the username and content of the second comment
Copy the code
/ / method
const {
    comments: [, {
        content,
        user: {
            name
        }
    }]
} = article;
/ / method 2
const {
    content,
    user: {
        name
    }
} = article.comments[1]
Copy the code

It can be used flexibly.

For iteration and deconstruction

for(let { user: { name }, content } of article.comments) {
    console.log(name, content);
}
Copy the code

Using the example above, it is easy to deconstruct the specific properties of each object in the array with for-of.

Because for-OF can only iterate over data types that implement the Iterable interface, it cannot be used on ordinary objects.

const obj = {
    a: 1.b: 2
}
for(let prop of obj) {
    console.log(prop);
}
// Uncaught TypeError: obj is not iterable
Copy the code

Parameters of deconstruction

function print({ name, age, sex, address: { province, city } }) {
    console.log(name, age, sex, province, city);    
}

print({
    name: "herb".age: 19.sex: "Male".address: {
        province: "Zhejiang".city: "Jiaxing"}});Copy the code

You can destruct the parameter directly, eliminating the need to repeatedly call the object to get the value. And it doesn’t affect arguments, it still holds the objects passed in.

function ajax({
    method = "get",
    url = "/"
} = {}) {
    console.log(method, url);
}
ajax({
    method: "get".url: "www.juejin.cn"
})
Copy the code

Use the default value in the deconstruction, allowing for cases where the object passed in does not have this property. Set default values for parameters to prevent undefined from being deconstructed without passing objects in. Code becomes concise and robust.