Destructuring is a convenient way of extracting values from data stored in (possibly nested) objects and Arrays.
var a, b, rest;
[a, b] = [1, 2];
console.log(a); // 1
console.log(b); // 2
[a, b, ...rest] = [1, 2, 3, 4, 5];
console.log(a); // 1
console.log(b); // 2
console.log(rest); // [3, 4, 5]Object destructuring
Destructuring objects:
const obj = {total: 42, isValid: true};
const {total, isValid} = obj;
console.log(total); // 42
console.log(isValid); // trueA variable can be extracted from an object and assigned to a variable with a different name than the object property.
const obj = {total: 42, isValid: true};
const {total: tot, isValid: valid} = obj;
console.log(tot); // 42
console.log(valid); // trueNested object and array destructuring
var metadata = {
title: "Scratchpad",
translations: [
{
last_edit: "2014-04-14T08:43:37",
url: "/de/docs/Tools/Scratchpad",
title: "JavaScript-Umgebung"
}
]
};
var { title, translations: [{ last_edit }] } = metadata;
console.log(title); // Scratchpad
console.log(last_edit); // 2014-04-14T08:43:37Array destructuring
Basic variable assignment
var valueArray = ["one", "two", "three"];
var [one, two, three] = valueArray;
console.log(one); // one
console.log(two); // two
console.log(three); // threeA variable can be assigned a default, in the case that the value pulled from the array is undefined.
var [one="one", two="two"] = ["1"];
console.log(one); // 1
console.log(two); // twoWhen the regular expression exec() method finds a match, it returns an array containing first the entire matched portion of the string and then the portions of the string that matched each parenthesized group in the regular expression.
Destructuring assignment allows you to pull the parts out of this array easily, ignoring the full match if it is not needed.
const [all, year, month, day] = /^(\d\d\d\d)-(\d\d)-(\d\d)$/.exec('1999-12-28');
console.log(all); // 1999-12-28
console.log(year); // 1999
console.log(month); // 12
console.log(day); // 28Usage
We can also destructure in a for-of loop:
const user = [
{name: 'saravana', age: 31},
{name: 'kumar', age: 29},
];
for (const {name, age} of user) {
console.log(name, age);
}
// saravana 31
// kumar 29