Percursos
/
JavaScript
JavaScript
/
Programa
/
Desestruturação de objetos
De

Desestruturação de objetos em JavaScript

1 exercício

Sobre Desestruturação de objetos

A desestruturação de objetos é uma forma concisa de extrair propriedades de um objeto. A sua sintaxe é semelhante à 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;
// => '🌩️'

Mudar o nome na atribuição

A sintaxe pode extrair as propriedades pela sua 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;
// => 🌧️

Não é obrigatório usar todos os valores na atribuição.

Valores predefinidos

A atribuição por desestruturação de objetos pode fornecer valores predefinidos caso não exista nenhum no objeto de origem:

const { sun = '🌞', tornado = '🌪️', cloud_with_snow: snowy = '❄️' } = weather;

sun;
// => '☀️'

tornado;
// => '🌪️'

snowy;
// => '🌨️'

Observa-se o seguinte:

  • sun foi extraída do objeto weather sem ser substituída, pois está presente no objeto weather;
  • tornado não existe no objeto weather, por isso foi usado o valor predefinido;
  • cloud_with_snow foi extraída como a variável snowy, sem ser substituída, pois cloud_with_snow está presente no objeto weather.

Desestruturar parâmetros de funções

O objeto weather tem imensas propriedades. É possível extrair diretamente uma ou várias propriedades deste objeto quando este é passado a uma função:

function weatherReport({ sun }) {
  console.log(sun);
}

weatherReport(sun);
// => '☀️'

Desestruturar a iteração 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.'

Conceitos relacionados

array-destructuring rest-and-spread

Editar via GitHub A ligação abre numa nova janela ou separador

Aprende Desestruturação de objetos