“This is the 15th day of my participation in the November Gwen Challenge. See details of the event: The Last Gwen Challenge 2021”.

Object deconstruction

Let’s say I have an object like this

    const userInfo = {
        name: 'lisi',
        age: 15,
        gender: 'male'
    }
    
Copy the code

You want to get all the values, that’s all you can do without deconstructing the assignment

console.log(userInfo.name); Print them out one by one.Copy the code

Or do this,

 for(let key in userInfo) {
    console.log(`${ key }:${ userInfo[key] }`);
}
Copy the code

It still looks a little bit fussy.

But with deconstruction assignment, things are much easier.

Const {name, age, gender} = userInfo looks more intuitiveCopy the code

Of course, this is just the simplest application.

There is a case where the back end will return you this data (although this is probably not the case at all). const data = { result: { data: { userInfo: { name: 'lisi', age: 15, gender: 'male' } } } }Copy the code

What would you do if you wanted to get the name,age,gender of the innermost layer.

  const { userInfo } = data.result.data
  const { name, age, gender } = userInfo
  
Copy the code

Some of you might do that, you know, splat two lines of code.

But it’s not very good. The code is so easy to read that it doesn’t show up. (KKKK, just kidding)

so

 const  { result: { data: { userInfo: { name, age, gender } } } } = data
 
Copy the code

It looks very classy

Well, I’m just kidding. The point is,

Objects are deconstructed from left to right. For example,

const { name } = userInfo
Copy the code

The userInfo object will find the key name name, and then check if the name in parentheses follows the variable name. If so, assign the value to the variable name. If not, the variable name will remain the same.

const { name: newName } = userInfo
console.log(name, newName);

ReferenceError: name is not defined
Copy the code

It is the latter that is really assigned.

Objects can also be destructed using default values

const userInfo = {

}
const { name = 'caiji', age = '16', gender = 'male' } = userInfo
console.log(name);
Copy the code

Strings can also be used for deconstruction

   const [a,b,c] = 'hello'
   const { length: len } = 'hello'
   console.log(a,b,c,len);
   
Copy the code

Guess what the output is?

H e L 5 because every array-like object has a length property.Copy the code

Array deconstruction

Const [a,b,c] = [1,2,3,4] console.log(a,b,c); const [a,b,c] = [1,2,3,4] console.log(a,b,c); // 1,2,3Copy the code

Array deconstruction is often used to swap the values of two variables. Before this, we usually swapped two variables using an intermediate variable.

 let a = 1
let b = 2
let mid = b
  b = a
  a = mid
  console.log(a,b); 
Copy the code

It seems very complicated, but with deconstruction it becomes very simple

let a = 1;
let b = 2;
[a,b] = [b,a];
console.log(a,b);
Copy the code