المسارات
/
JavaScript
JavaScript
/
المنهج
/
تفكيك الكائنات
تف

تفكيك الكائنات في JavaScript

1 تمرين

نبذة عن تفكيك الكائنات

إن تفكيك الكائنات طريقة موجزة لاستخراج الخصائص من كائن. صياغته تشبه تعبير الكائن الحرفي، لكنه يقع على الجانب الأيسر من الإسناد بدل الجانب الأيمن.

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 دون استبدالها، لأنها موجودة في الكائن weather،
  • لا توجد 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.'

مفاهيم ذات صلة

array-destructuring rest-and-spread

تعديل عبر GitHub يفتح الرابط في نافذة أو علامة تبويب جديدة

تعلّم تفكيك الكائنات