It has to be said that deconstruction assignment is a sharp tool for the former engineers. It is both simple and powerful, with extremely strong practicality.

In real work scenarios, we often deal with deeply nested objects.

For example, if you are the principal of our school, there are three grades in our school. There are several classes in each grade. Each student in the class has a score of each subject.


let school = {
  grade1: {
    class1: {
      DaQiao: {
        Math: 91,
        Chinese: 93,
        Enlish: 82
      },
      XiaoQiao: {
        Math: 33,
        Chinese: 56,
        Enlish: 93
      }
    },
    class2: {
      SunQuan: {}
    }
  },
  grade2: {},
  grade3: {}
}
Copy the code

As we can see, Little Joe’s English scores are good, but math and Chinese scores are in a mess, while big Joe is excellent in all subjects, but English is a little inferior.

Since you are the principal and have the absolute power to change the test scores, Little Joe and Big Joe wondered if they could get you to change the test scores secretly.

Xiao Qiao is very poor in math and Chinese, so I hope you can help her add ten points to each of these two subjects. Big Joe wants you to improve her English by five points.

But you had your own rules, and you decided to change the test scores of only one of them, based on your own sexual feelings.

The code for this would look something like this:

if (dreamGirl === 'XiaoQiao') {
  school.grade1.class1.XiaoQiao.Math += 10
  school.grade1.class1.XiaoQiao.Chinese += 10
} else if (dreamGirl === 'DaQiao') {
  school.grade1.class1.DaQiao.English += 5
}
Copy the code

Obviously, this kind of deeply nested object can be very cumbersome to write, especially when the code logic becomes complex, in which case we can use destruct assignment, like the following:

let {
  grade1: {
    class1: { DaQiao, XiaoQiao }
  }
} = school
 
if (dreamGirl === 'XiaoQiao') {
  XiaoQiao.Math += 10
  XiaoQiao.Chinese += 10
} else if (dreamGirl === 'DaQiao') {
  DaQiao.English += 5
}
Copy the code

One might ask, isn’t the new variable in the deconstruction assignment, and does this change the value of the original school object?

In fact, this is why we deconstruct only to DaQiao and XiaoQiao layer, rather than continue to deconstruct to Math, Chinese, English layer. Because our newly created DaQiao and XiaoQiao the two objects is the original object reference, in other words, is two Pointers, and school respectively. Grade1. Class1. DaQiao, School. Grade1. Class1. XiaoQiao point to the same memory address. If we continue to deconstruct, the variables we get are copies of the values, and we can change the Math, Chinese, and English values without affecting the original school object.