Как правильно деструктурировать сложный объект

Рейтинг: 0Ответов: 2Опубликовано: 21.01.2023
function calculateMeanTemperature(forecast) {
  const todayLow = forecast.today.low;
  const todayHigh = forecast.today.high;
  const tomorrowLow = forecast.tomorrow.low;
  const tomorrowHigh = forecast.tomorrow.high;

  // Change code above this line
  return (todayLow + todayHigh + tomorrowLow + tomorrowHigh) / 4;
}

Функция calculateMeanTemperature(forecast) принимает один параметр forecast – объект температур на два дня следующего формата.

{
  today: { low: 10, high: 20 },
  tomorrow: { low: 20, high: 30 }
}

Замени объявления переменных todayLow, todayHigh, tomorrowLow и tomorrowHigh одной операцией деструктуризации свойств объекта forecast.

Условия:

  • Объявленная функция calculateMeanTemperature(forecast)

  • В теле функции используется деструктуризация объекта

  • В теле функции объявлена ​​переменная todayHigh с помощью деструктуризации

  • В теле функции объявлена ​​переменная todayLow с помощью деструктуризации

  • В теле функции объявлена ​​переменная tomorrowLow посредством деструктуризации

  • В теле функции объявлена ​​переменная tomorrowHigh с помощью деструктуризации

Тесты:

  • Вызов calculateMeanTemperature({ today: {low: 28, high: 32}, tomorrow: {low: 25, high: 29} }) возвращает 28.5

  • Вызов calculateMeanTemperature({ today: {low: 37, high: 40}, tomorrow: {low: 33, high: 38} }) возвращает 37

Ответы

▲ 1Принят

Ну тут не один способ деструктуризации можно применить:

  1. Самый простой и очевидный - просто перечисляем какой переменной что достанется:

    const data = {
      today: { low: 10, high: 20 },
      tomorrow: { low: 20, high: 30 }
    };
    
    function calculateMeanTemperature(forecast) {
      const [
        todayLow,
        todayHigh,
        tomorrowLow,
        tomorrowHigh
      ] = [
        forecast.today.low,
        forecast.today.high,
        forecast.tomorrow.low,
        forecast.tomorrow.high,
      ]
    
      // Change code above this line
      return (todayLow + todayHigh + tomorrowLow + tomorrowHigh) / 4;
    }
    
    console.log(calculateMeanTemperature(data));

  2. Деструктурировать в 2 этапа. Сначала для today, а потом для tomorrow

    const data = {
      today: { low: 10, high: 20 },
      tomorrow: { low: 20, high: 30 }
    };
    
    function calculateMeanTemperature(forecast) {
      const {low: todayLow, high: todayHigh} = forecast.today;
      const {low: tomorrowLow, high: tomorrowHigh} = forecast.tomorrow;
    
      // Change code above this line
      return (todayLow + todayHigh + tomorrowLow + tomorrowHigh) / 4;
    }
    
    console.log(calculateMeanTemperature(data));

  3. Тоже самое что и во втором, только today и tomorrow деструктруируем отдельно:

    const data = {
      today: { low: 10, high: 20 },
      tomorrow: { low: 20, high: 30 }
    };
    
    function calculateMeanTemperature(forecast) {
      const {today, tomorrow} = forecast;
      const {low: todayLow, high: todayHigh} = today;
      const {low: tomorrowLow, high: tomorrowHigh} = tomorrow;
    
      // Change code above this line
      return (todayLow + todayHigh + tomorrowLow + tomorrowHigh) / 4;
    }
    
    console.log(calculateMeanTemperature(data));

  4. Почти как первый, в том плане, что опять перечисляем по одному для всех, но уже деструктурируем как объект:

    const data = {
      today: { low: 10, high: 20 },
      tomorrow: { low: 20, high: 30 }
    };
    
    function calculateMeanTemperature(forecast) {
      const {
        today: {low: todayLow, high: todayHigh},
        tomorrow: {low: tomorrowLow, high: tomorrowHigh}
      } = forecast;
    
      // Change code above this line
      return (todayLow + todayHigh + tomorrowLow + tomorrowHigh) / 4;
    }
    
    console.log(calculateMeanTemperature(data));

▲ 0
function calculateMeanTemperature(forecast) {
 const{
  today: {low:todayLow, high: todayHigh},
  tomorrow: {low:tomorrowLow, high: tomorrowHigh
 }} = forecast;

  // Change code above this line
  return (todayLow + todayHigh + tomorrowLow + tomorrowHigh) / 4;
}