オブジェクトの分割代入は、オブジェクトからプロパティを抽出する簡潔な方法です。その構文はオブジェクトリテラル式に似ていますが、代入の右辺ではなく左辺に書きます。
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オブジェクトには多くのプロパティがあります。このオブジェクトが関数に渡されたときに、1つまたは複数のプロパティを直接抽出できます。
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.'