Tracce
/
JavaScript
JavaScript
/
Programma
/
Destrutturazione degli oggetti
De

Destrutturazione degli oggetti in JavaScript

1 esercizio

Informazioni su Destrutturazione degli oggetti

La destrutturazione degli oggetti è un modo conciso per estrarre le proprietà da un oggetto. La sua sintassi è simile a un'espressione con oggetto letterale, ma si trova sul lato sinistro dell'assegnazione invece che sul destro.

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;
// => '🌩️'

Rinominare nell'assegnazione

La sintassi può estrarre le proprietà in base alla loro chiave, come sun, cloud e cloud_with_lightning, ma può anche scegliere un nome diverso per la variabile:

const { sun: sunny, cloud: cloudy, cloud_with_rain: rainy } = weather;

typeof cloud_with_rain;
// => 'undefined'

typeof rainy;
// => 'string'

rainy;
// => 🌧️

Inoltre, non è obbligatorio che l'assegnazione usi tutti i valori.

Valori predefiniti

L'assegnazione con destrutturazione di oggetti può fornire valori predefiniti nel caso in cui non ce ne sia nessuno nell'oggetto di origine:

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

sun;
// => '☀️'

tornado;
// => '🌪️'

snowy;
// => '🌨️'

Si osserva quanto segue:

  • sun è stato estratto dall'oggetto weather senza sostituirlo, poiché è presente nell'oggetto weather,
  • tornado non esiste nell'oggetto weather, quindi è stato usato il valore predefinito,
  • cloud_with_snow è stato estratto come variabile snowy, senza sostituirlo, poiché cloud_with_snow è presente nell'oggetto weather.

Destrutturazione dei parametri di una funzione

L'oggetto weather ha molte proprietà. È possibile estrarre direttamente una o più proprietà da questo oggetto quando viene passato a una funzione:

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

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

Destrutturazione nell'iterazione for of

Quando si itera su un array (o un altro iterabile) e gli elementi sono oggetti, è possibile destrutturare all'interno dell'istruzione 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.'

Concetti correlati

array-destructuring rest-and-spread

Modifica tramite GitHub Il collegamento si apre in una nuova finestra o scheda

Impara Destrutturazione degli oggetti