concept
The destruct assignment syntax is a Javascript expression. By deconstructing assignments, attributes/values can be taken from objects/arrays and assigned to other variables.
An array of deconstruction
let [a,b]=[1.2]
// a = 1
// b = 2
Copy the code
React is often used with const [value,setValue]=useState(” “).
Assign the remaining array to a variable
When deconstructing an array, you can use the remainder pattern to assign the remainder of the array to a variable.
var [a, ...b] = [1, 2, 3];
// a = 1
// b = [2, 3]
Copy the code
Deconstructing defaults
If the deconstructed value is undefined, the default value can be set:
let a, b; // Set the default value [a = 9, b = 7] = [1, 2]; // a = 9 // b = 7Copy the code
Switching variable
You can swap the values of two variables in a destructed expression.
Swapping two variables without a deconstructed assignment requires a temporary variable (or the Low-level xor-swap technique).
var a = 1;
var b = 3;
[a, b] = [b, a];
// a = 3
// b = 1
Copy the code
Ignore some return values
You can also ignore return values that you are not interested in:
function f() {
return [1, 2, 3];
}
var [a, , b] = f();
// a = 1
// b = 3
Copy the code
You can even ignore them all:
[,,] = f();
Copy the code
Deconstruction object
Rename and assign default values
const { a:k = 2 } = { a: 1 }
// k = 1
const { a:k = 2 } = { a: null }
// k = null
const { a: k = 2 } = { a: undefined }
// k = 2
Copy the code
So careful on the top, simple on the bottom:
Nested objects and array destructions
//
const metadata = {
title: 'Scratchpad'.translations: [{locale: 'de'.localization_tags: [].last_edit: '2014-04-14T08:43:37'.url: '/de/docs/Tools/Scratchpad'.title: 'JavaScript-Umgebung'}].url: '/en-US/docs/Tools/Scratchpad'
};
let {
title: englishTitle, // rename
translations: [{title: localeTitle, // rename
},
],
} = metadata;
console.log(englishTitle); // "Scratchpad"
console.log(localeTitle); // "JavaScript-Umgebung"
Copy the code
Object property name destruct
let key = "z";
let { [key]: foo } = { z: "bar" };
console.log(foo); // "bar"
Copy the code
Invalid JavaScript identifier as property name
Destructuring can be used with property names that are not valid JavaScript identifiers by providing valid alternative identifiers.
const foo = { 'fizz-buzz': true };
const { 'fizz-buzz': fizzBuzz } = foo;
// Use the following syntax
// const { fizz-buzz: fizzBuzz } = foo;
console.log(fizzBuzz); // true
Copy the code
Reference article:
MDN