Destructuring
Destructuring is a way of teasing apart collections and assigning the component values to variables.
Table of Contents
- Destructuring Arrays
- Destructuring Function Return Values
- Destructuring Objects
- Destructuring Nested Data
- Complex Nested Data
Destructuring Arrays
Instead of indexed array assignment:
const hearts = ["π€", "β€οΈ", "π"];
const black = hearts[0];
const red = hearts[1];
const yellow = hearts[2];
console.log(yellow); // π
With destructuring syntax we can write:
const hearts = ["π€", "β€οΈ", "π"];
const [black, red, yellow] = hearts;
console.log(yellow); // π
Destructuring Function Return Values
Letβs say you a function named weather that returns an array of three temperatures.
const temperatures = weather(); // [10, 15, 22]
And you know that the forecasted low, high, and average temperature appear in that order in the array.
You can destructure the returned array into the variables low, high, and average:
const [low, high, average] = weather(); // [10, 15, 22]
console.log(`Average: ${average} Low: ${low} High: ${high} `);
// Average: 22 Low: 10 High: 15
Destructuring Objects
We can also promote object keys to variables using destructuring:
const adventures = { mountain: "β°οΈ", desert: "ποΈ" };
const { mountain, desert } = adventures;
console.log(mountain); // β°οΈ
console.log(desert); // ποΈ
We can also name the variables sometime different from the object keys:
const { mountain: everest, desert: sahara } = adventures;
console.log(sahara); // ποΈ
console.log(everest); // β°οΈ
Destructuring Nested Data
Destructuring can also be used to pluck data out of nested data structures, like an array of objects:
const animalFriends = [
{ name: "Monkey", emoji: "π" },
{ name: "Dog", emoji: "π" },
{ name: "Cow", emoji: "π" },
];
// - Skip the zeroth position in the array with a comma.
// - Grab the emoji out of the object at first position.
// - Skip the object in the final position of the array.
const [, { emoji: dogEmoji }] = animalsFriends;
console.log(dogEmoji); // π
Complex Nested Data
This example from the MDN shows the destructuring of the kind of object you might get back from an API:
// Let's pretend this data came from an API.
const apiResponse = {
title: "JS Environment",
translations: [
{
locale: "de - Germany",
last_edit: "2014-04-14T08:43:37",
title: "JS Umgebung",
},
],
};
// Pluck the English and German title from the data.
let {
title: englishTitle,
translations: [{ title: localeTitle }],
} = apiResponse;
console.log(englishTitle); // "JS Environment"
console.log(localeTitle); // "JS Umgebung"