Az objektumok destrukturálása tömör módja annak, hogy tulajdonságokat nyerjünk ki egy objektumból. A szintaxisa hasonlít egy objektumliterál kifejezéshez, de az értékadás bal oldalán áll, nem a jobboldalin.
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 szintaxis a kulcsuk alapján is ki tudja nyerni a tulajdonságokat, például a sun, a cloud és a cloud_with_lightning esetében, de más nevet is adhat a változónak:
const { sun: sunny, cloud: cloudy, cloud_with_rain: rainy } = weather;
typeof cloud_with_rain;
// => 'undefined'
typeof rainy;
// => 'string'
rainy;
// => 🌧️
Az értékadásnak nem is kell az összes értéket felhasználnia.
Az objektum-destrukturáló értékadás alapértelmezett értékeket is megadhat arra az esetre, ha a forrásobjektumban nincs ilyen:
const { sun = '🌞', tornado = '🌪️', cloud_with_snow: snowy = '❄️' } = weather;
sun;
// => '☀️'
tornado;
// => '🌪️'
snowy;
// => '🌨️'
Az alábbiakat figyelhetjük meg:
sun ki lett nyerve a weather objektumból, és nem cserélődött le, mert szerepel a weather objektumban,tornado nem létezik a weather objektumban, ezért az alapértelmezett érték lépett a helyére,cloud_with_snow a snowy változóba lett kinyerve, és nem cserélődött le, mert a cloud_with_snow szerepel a weather objektumban.A weather objektumnak sok tulajdonsága van.
Az is lehetőség, hogy közvetlenül kinyerj egy vagy több tulajdonságot ebből az objektumból, amikor átadod egy függvénynek:
function weatherReport({ sun }) {
console.log(sun);
}
weatherReport(sun);
// => '☀️'
for of iterációbanAmikor egy array (vagy más iterálható) elemein mégy végig, és az elemek objektumok, a for (...) of iterable utasításon belül is destrukturálhatsz:
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.'