Detailed Explanation of Deconstruction Assignment Syntax in Javascript

  • 2021-11-01 23:32:14
  • OfStack

Preface

The "deconstructed assignment syntax" first introduced in ES 6 allows values from arrays and objects to be inserted into different variables. Although it may seem difficult, it is actually easy to learn and use.

Deconstruction assignment syntax is an JS expression. ES6 allows you to extract values from arrays and objects and assign values to variables according to the 1-determined pattern, which is called deconstruction. By deconstructing assignment, attributes/values can be taken out of objects/arrays and assigned to other variables.

Before ES6 deconstruction assignment, when we need to assign values to variables, we can only specify values directly.

For example:


let a = 1;
let b = 2;
let c = 3;
let d = 4;
let e = 5;

Array deconstruction is very simple. All you have to do is declare one variable for each value in the array. You can define fewer variables than indexes in an array (that is, if you only want to solve the first few values), skip some indexes or even use REST mode to put all the remaining values into a new array.


const nums = [ 3, 6, 9, 12, 15 ];
const [
 k,    // k = 3
 l,    // l = 6
 ,    // Skip a value (12)
 ...n   // n = [12, 15]
] = nums;

Object deconstruction

Object deconstruction is very similar to array deconstruction, except that each key in an object can be referenced by name to create a variable with the same name. You can also deconstruct keys into new variable names, deconstruct only the required key, and then use the rest schema to deconstruct the remaining key into new objects.


const obj = { a: 1, b: 2, c: 3, d: 4 };
const {
 a,       // a = 1
 c: d,      // d = 3
 ...rest     // rest = { b: 2, d: 4 }
} = obj;

Nested deconstruction

Nested objects and arrays can be deconstructed by the same rules. The difference is that nested key or values can be deconstructed directly as variables without storing the parent object in the variable itself.


const nested = { a: { b: 1, c: 2 }, d: [1, 2]};
const {
 a: {
  b: f,     // f = 1
  ...g     // g = { c: 2 }
 },
 ...h      // h = { d: [1, 2]}
} = nested;

Advanced deconstruction

Because arrays behave like objects, you can get specific values from arrays using deconstruction allocation syntax by using indexes as key in object deconstruction allocation. In this way, you can also get other attributes of the array (such as length of the array). Finally, if the deconstructed value is undefined, you can also define default values for variables during deconstruction.


const arr = [ 5, 'b', 4, 'd', 'e', 'f', 2 ];
const {
 6: x,      // x = 2
 0: y,      // y = 5
 2: z,      // z = 4
 length: count, // count = 7
 name = 'array', // name = 'array' (not present in arr)
 ...restData   // restData = { '1': 'b', '3': 'd', '4': 'e', '5': 'f' }
} = arr;

Summarize


Related articles: