A desestruturação de objetos é uma forma concisa de extrair propriedades de um objeto. Sua sintaxe é parecida com a de uma expressão de objeto literal, mas do lado esquerdo da atribuição em vez do direito.
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;
// => '🌩️'
A sintaxe pode extrair as propriedades pela chave, como sun, cloud e cloud_with_lightning, mas também pode escolher um nome diferente para a variável:
const { sun: sunny, cloud: cloudy, cloud_with_rain: rainy } = weather;
typeof cloud_with_rain;
// => 'undefined'
typeof rainy;
// => 'string'
rainy;
// => 🌧️
A atribuição também não precisa usar todos os valores.
A atribuição por desestruturação de objeto pode fornecer valores padrão caso não exista nenhum no objeto de origem:
const { sun = '🌞', tornado = '🌪️', cloud_with_snow: snowy = '❄️' } = weather;
sun;
// => '☀️'
tornado;
// => '🌪️'
snowy;
// => '🌨️'
Observe o seguinte:
sun foi extraído do objeto weather sem ser substituído, pois está presente no objeto weather,tornado não existe no objeto weather, então o valor padrão foi usado,cloud_with_snow foi extraído como a variável snowy, sem ser substituído, pois cloud_with_snow está presente no objeto weather.O objeto weather tem muitas propriedades.
É possível extrair diretamente uma ou várias propriedades desse objeto quando ele é passado para uma função:
function weatherReport({ sun }) {
console.log(sun);
}
weatherReport(sun);
// => '☀️'
for of
Ao iterar sobre um array (ou outro iterável), e quando os itens são objetos, é possível desestruturar dentro da instrução 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.'