Object destructuring is a concise way of extracting properties from an object. Its syntax is similar to an object literal expression, but on the left-hand side of the assignment instead of the right.
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;
// => 'đŠī¸'
The syntax can extract the properties by their key like sun
, cloud
, and cloud_with_lightning
, but can also pick a different name for the variable:
const { sun: sunny, cloud: cloudy, cloud_with_rain: rainy } = weather;
typeof cloud_with_rain;
// => 'undefined'
typeof rainy;
// => 'string'
rainy;
// => đ§ī¸
The assignment is also not required to use all the values.
The object destructuring assignment can provide default values in case there is none in the source object:
const { sun = 'đ', tornado = 'đĒī¸', cloud_with_snow: snowy = 'âī¸' } = weather;
sun;
// => 'âī¸'
tornado;
// => 'đĒī¸'
snowy;
// => 'đ¨ī¸'
The following is observed:
sun
has extracted from the object weather
without replacing it as it is present in the object weather
,tornado
does not exist in the object weather
, so the default value was used,cloud_with_snow
was extracted as the variable snowy
, without replacing it, as cloud_with_snow
is present in the object weather
.The weather
object has a lot of properties.
It is possible to directly extract one or multiple properties from this object when it's passed to a function:
function weatherReport({ sun }) {
console.log(sun);
}
weatherReport(sun);
// => 'âī¸'
for of
iterationWhen iterating over an array
(or other iterable), and the items are objects, it is possible to destructure inside the for (...) of iterable
statement:
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.'