객체 구조 분해는 객체에서 속성을 추출하는 간결한 방법이에요. 문법은 객체 리터럴 표현식과 비슷하지만, 할당의 오른쪽이 아니라 왼쪽에 온다는 점이 달라요.
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에 값이 있으므로 기본값으로 대체되지 않고 그대로 추출됐어요,tornado는 객체 weather에 없어서 기본값이 사용됐어요,cloud_with_snow는 객체 weather에 값이 있으므로 대체되지 않고 snowy라는 변수로 추출됐어요.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.'