Деструктуризація обʼєктів дає змогу стисло вилучати властивості з обʼєкта. Її синтаксис подібний до виразу обʼєктного літерала, але стоїть у лівій частині присвоєння, а не в правій.
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;
// => '🌩️'
Цей синтаксис може вилучати властивості за їхнім ключем, як-от sun, cloud і cloud_with_lightning, але також може дати змінній інше імʼя:
const { sun: sunny, cloud: cloudy, cloud_with_rain: rainy } = weather;
typeof cloud_with_rain;
// => 'undefined'
typeof rainy;
// => 'string'
rainy;
// => 🌧️
Присвоєння також не зобовʼязує використовувати всі значення.
Присвоєння з деструктуризацією обʼєкта може надати типові значення, якщо у вихідному обʼєкті їх немає:
const { sun = '🌞', tornado = '🌪️', cloud_with_snow: snowy = '❄️' } = weather;
sun;
// => '☀️'
tornado;
// => '🌪️'
snowy;
// => '🌨️'
Можна помітити таке:
sun вилучено з обʼєкта weather, і його не замінено, оскільки він присутній в обʼєкті weather;tornado не існує в обʼєкті weather, тому використано типове значення;cloud_with_snow вилучено у змінну snowy без заміни, оскільки cloud_with_snow присутній в обʼєкті weather.Обʼєкт weather має багато властивостей.
Можна безпосередньо вилучити одну або кілька властивостей з цього обʼєкта, коли його передають у функцію:
function weatherReport({ sun }) {
console.log(sun);
}
weatherReport(sun);
// => '☀️'
for of
Коли ми перебираємо array (або інший обʼєкт, який можна перебрати), а елементи є обʼєктами, можна виконувати деструктуризацію всередині інструкції 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.'