অবজেক্ট ডিস্ট্রাকচারিং হলো কোনো অবজেক্ট থেকে প্রপার্টি এক্সট্র্যাক্ট করার একটি সংক্ষিপ্ত উপায়। এর সিনট্যাক্স একটি অবজেক্ট লিটারাল এক্সপ্রেশনের মতোই, তবে তা অ্যাসাইনমেন্টের ডান দিকে নয়, বাম দিকে থাকে।
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-এর মতো কী (key) দিয়ে প্রপার্টি এক্সট্র্যাক্ট করতে পারে, আবার ভ্যারিয়েবলের জন্য ভিন্ন নামও বেছে নিতে পারে:
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 অবজেক্ট থেকে এক্সট্র্যাক্ট করা হয়েছে,weather অবজেক্টে tornado নেই, তাই ডিফল্ট মানটি ব্যবহার করা হয়েছে,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.'