ऑब्जेक्ट डीस्ट्रक्चरिंग ऑब्जेक्ट से प्रॉपर्टी निकालने का एक संक्षिप्त तरीका है। इसका सिंटैक्स ऑब्जेक्ट लिटरल एक्सप्रेशन जैसा ही होता है, बस इसे असाइनमेंट के दाईं ओर नहीं, बाईं ओर लिखा जाता है।
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 से निकाला गया और चूँकि sun उस ऑब्जेक्ट में मौजूद है, इसलिए उसकी वैल्यू बदली नहीं गई,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.'