La desestructuración de objetos es una forma concisa de extraer propiedades de un objeto. Su sintaxis es similar a la de una expresión de objeto literal, pero en el lado izquierdo de la asignación en lugar del derecho.
const weather = {
sun: '☀️',
sun_behind_small_cloud: '🌤️',
sun_behind_cloud: '⛅',
sun_behind_large_cloud: '🌥️',
sun_behind_rain_cloud: '🌦️',
cloud: '☁️',
cloud_with_rain: '🌧️',
cloud_with_snow: '🌨️',
cloud_with_lightning: '🌩️',
cloud_with_lightning_and_rain: '⛈️',
};
const { sun, cloud, cloud_with_lightning } = weather;
sun;
// => '☀️'
cloud;
// => '☁️'
cloud_with_lightning;
// => '🌩️'
La sintaxis puede extraer las propiedades por su clave, como sun, cloud y cloud_with_lightning, pero también puede elegir un nombre distinto para la variable:
const { sun: sunny, cloud: cloudy, cloud_with_rain: rainy } = weather;
typeof cloud_with_rain;
// => 'undefined'
typeof rainy;
// => 'string'
rainy;
// => 🌧️
Además, la asignación no tiene por qué usar todos los valores.
La asignación por desestructuración de objetos puede proporcionar valores por defecto en caso de que no haya ninguno en el objeto de origen:
const { sun = '🌞', tornado = '🌪️', cloud_with_snow: snowy = '❄️' } = weather;
sun;
// => '☀️'
tornado;
// => '🌪️'
snowy;
// => '🌨️'
Se observa lo siguiente:
sun se ha extraído del objeto weather sin reemplazarlo, ya que está presente en el objeto weather,tornado no existe en el objeto weather, así que se ha usado el valor por defecto,cloud_with_snow se ha extraído como la variable snowy, sin reemplazarlo, ya que cloud_with_snow está presente en el objeto weather.El objeto weather tiene muchas propiedades.
Es posible extraer directamente una o varias propiedades de este objeto cuando se pasa a una función:
function weatherReport({ sun }) {
console.log(sun);
}
weatherReport(sun);
// => '☀️'
for of
Cuando se itera sobre un array (u otro iterable) y los elementos son objetos, es posible desestructurar dentro de la instrucción for (...) of iterable:
const { sun: sunny, cloud: cloudy, cloud_with_rain: rainy } = weather;
const prediction = [
{
chance: 0.8,
weather: sunny,
description: 'There is a 80% chance it will remain sunny.',
},
{
chance: 0.15,
weather: cloudy,
description:
'There is a 15% chance the clouds will keep the sun from poking through.',
},
{
chance: 0.05,
weather: rainy,
description: 'There is a small chance of rain.',
},
];
for (const { weather: symbol, description } of prediction) {
console.log(`${symbol}: ${description}`);
}
// '☀️: There is a 80% chance it will remain sunny.'
// '☁️: There is a 15% chance the clouds will keep the sun from poking through.'
// '🌧️: There is a small chance of rain.'