json 我如何为我的对象中的每个元素创建新的数组,该对象总共由四个数组组成,以动态生成一周的预测?

zaqlnxep  于 5个月前  发布在  其他
关注(0)|答案(1)|浏览(70)

我又回来了!我几乎完成了我最近的问题也来自同一个项目.我在路上遇到了巨大的颠簸.差不多,我现在正试图在我的应用程序中显示7天的预测.类似这样的东西:
x1c 0d1x的数据



然后,我有一个对象,它包含四个数组,每个数组有七个元素,这使得我需要一个7天的预测信息。该对象是这样的:



我知道我可以手动将7张卡片添加到预测的位置,但我想尝试用一个定义来生成它们,而不是手动定义7张卡片。我的第一个问题是,我根本不知道如何制作由四个元素组成的新数组,每个元素来自每个数组。以上面的例子中的[0]元素为例,我基本上希望它像这样,其中七个。元素依次为'time','weather_code','temperature_2m_min'和'temperature_2m_max':

daySpecs: [ "2023-12-09", 3, -12.9, -10]

字符串
这是我到目前为止的代码(当然是草稿),我可以重复使用并手动制作7张卡片:

<div className='weather-forecast'>

        <div className="card">
          <h3>{datesWeek[0]}</h3>
          <p>Temperature: {temperaturesMinWeek[0]}</p>
          <p>Weather: {wmo[weatherCodesWeek[0]]}</p>
        </div>
        <div className="card">
          <h3>{datesWeek[1]}</h3>
          <p>Temperature: {temperaturesMinWeek[1]}</p>
          <p>Weather: {wmo[weatherCodesWeek[1]]}</p>
        </div>

        </div>


这是我想找到一种方法来动态生成的一部分。你可以说,有两个问题在这个问题。我已经花了相当长的时间来尝试和弄清楚这一点,我得到了一点苦恼,我找不到任何网上类似或相同的问题,我有。我希望我没有穿我的欢迎这个网站只是然而,但这是一个更独特的问题,我想问一下也无妨。提前感谢任何可以提供帮助的人。老实说,我今天仍然需要吃饭,我希望你们能理解我的要求,或者告诉我最好的方法。相反,如果你甚至告诉我像我的代码示例中那样手工制作每张卡片已经是一种最佳的方法,那将是一段很长的旅程。
请让我知道,如果我的代码将需要更多的这一点,但是,我的这个项目的很多代码可以在我以前的问题也找到。
编辑:我被要求发布一些代码,所以我会把所有的代码都放进去,因为这比放一部分代码容易:
App.jsx:

import { useState, useEffect } from 'react';
import axios from 'axios';
import "./App.css";
import Highcharts from 'highcharts';
import wmo from "./wmo.js"

function App() {
  const [weather, setWeather] = useState({});
  const hourlyTemperaturesOneWeek = weather.hourly?.temperature_2m;
  const [isFahrenheit, setIsFahrenheit] = useState(false);
  const [loading, setLoading] = useState(true);

  function getWeather() {
    axios.get('https://api.open-meteo.com/v1/forecast?latitude=65.01&longitude=25.47&current=temperature_2m,weather_code&hourly=temperature_2m&daily=weather_code,temperature_2m_max,temperature_2m_min&timezone=auto')
      .then(response => {
        setWeather(response.data);
        setLoading(false);
      })
      .catch(error => {
        console.error(error);
        setLoading(false);
      });
  }
  
  useEffect(() => {
    getWeather();
  }, []);

  const hoursOneWeek = weather.hourly?.time;

  const currentTemperature = !isFahrenheit 
  ? weather.current?.temperature_2m 
  : (weather.current?.temperature_2m * 9/5) + 32;

  const currentWeatherCodeLabel = wmo[weather.current?.weather_code];

  const weatherCodesWeek = weather.daily?.weather_code;
  const temperaturesMinWeek = weather.daily?.temperature_2m_min;
  const temperaturesMaxWeek = weather.daily?.temperature_2m_max;
  const datesWeek = weather.daily?.time;
  const sevenDayForecast = weather.daily;

  const date = new Date();
  const day = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][new Date().getDay()];

  const todayDate = date.getDate();
  const month = date.getMonth() + 1;
  const year = date.getFullYear();

  const hours = date.getHours();
  const minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();

  const formattedDate = todayDate + ' ' + getMonthName(month) + ' ' + year + ', ' + hours + ':' + minutes;

function getMonthName(month) {
    let monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
    return monthNames[month - 1];
}

  console.log(formattedDate);
  console.log(hourlyTemperaturesOneWeek);
  console.log(hoursOneWeek);
  console.log(currentTemperature);
  console.log(date);
  console.log(day);
  console.log(wmo);
  console.log(currentWeatherCodeLabel);
  console.log(weatherCodesWeek);
  console.log(temperaturesMinWeek);
  console.log(temperaturesMaxWeek);
  console.log(datesWeek);
  console.log(sevenDayForecast);

  const temperatures = isFahrenheit 
  ? hourlyTemperaturesOneWeek.map(temp => (temp * 9/5) + 32)
  : hourlyTemperaturesOneWeek;

  const tempUnit = isFahrenheit ? '°F' : '°C';

  useEffect(() => {
    Highcharts.chart('weather-chart', {
      title: {
          text: 'Temperatures (' + tempUnit + ')'
      },
      xAxis: {
        type: 'datetime',
        tickInterval: 24 * 3600 * 1000
      },
      yAxis: {
          title: {
              text: 'Temperature (' + tempUnit + ')'
          }
      },
      plotOptions: {
          series: {
              label: {
                  connectorAllowed: false
              },
              pointStart: date.setHours(2,0,0,0)
          }
      },
      credits: {
        enabled: false
      },
      series: [{
          name: 'Temperature (' + tempUnit + ')',
          data: temperatures,
          pointInterval:  3600 * 1000
      }],
      responsive: {
          rules: [{
              condition: {
                  maxWidth: 500
              },
              chartOptions: {
                  legend: {
                      layout: 'horizontal',
                      align: 'center',
                      verticalAlign: 'bottom'
                  }
              }
          }]
      }
  });
  });

  const viewportHeight = window.innerHeight;
  const responsiveHeight = (350 / viewportHeight) * 100;

  return (
    <div>
      {loading === true && !weather ? <p>Retrieving weather data. Please wait.</p> : null}
      <div className='flex-container'>
      <h1 className='weather-label'>Weather</h1>
      <div className='content-box' style={{height: responsiveHeight + 'vh'}}>
          <h2 className='current-weather-title'>Current weather</h2>
          <div className='current-temperature-label'>
              {Math.round(currentTemperature * 10) / 10 + ' ' + tempUnit} 
          </div>
          <div className='current-datetime-label'>
            {currentWeatherCodeLabel}
            <br></br>
            <br></br>
              {day + ', ' + formattedDate}
          </div>
      </div>
      </div>
      {weather ? (
        <><div className='weather-line-chart' id='weather-chart'>
        </div>
        <button className='toggle-button' onClick={() => setIsFahrenheit(prev => !prev)}>Toggle Temperature Unit</button>
        <div className='weather-forecast'>

        <div className="card">
          <h3>{datesWeek[0]}</h3>
          <p>Temperature: {temperaturesMinWeek[0]}</p>
          <p>Weather: {wmo[weatherCodesWeek[0]]}</p>
        </div>
        <div className="card">
          <h3>{datesWeek[1]}</h3>
          <p>Temperature: {temperaturesMinWeek[1]}</p>
          <p>Weather: {wmo[weatherCodesWeek[1]]}</p>
        </div>

        </div>
        </>
      ) : null}
    </div>
  );
}


样式文件:

body {
  background: linear-gradient(to bottom,#2546ff, #2546ff, white);
}

.weather-label {
  position: absolute;
  left: 2%;
  top: 0;
 }

.weather-line-chart {
  position: absolute;
  bottom: 0;
  right: 3%;
  width: 60%;

  height: 50vh;
}

.toggle-button {
  position: absolute;
  bottom: 2%;
  left: 7.8%;
}

.content-box {
  background-color: #f9f9f9;
  border: 1px solid #ddd;
  border-radius: 20px;
  padding: 20px;
  width: 160%;
  margin-left: 10%;
}

.current-weather-title {
  color: black;
  text-align: center;
}

.current-temperature-label {
  color: black;
  text-align: center;
  font-size: 3.125rem;
  font-weight: 900;
}

.current-datetime-label {
  color: black;
  text-align: center;
  font-size: 15px;
  font-weight: 500;
}

.weather-forecast {
  top: 15%;
  right: 10%;
  position: absolute;
  display: grid;
  grid-template-columns: repeat(7, 0fr);
  grid-gap: 10px;
  margin: 5px;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 20px;
  background-color: #f9f9f9;
}

.card {
  padding: 10px;
  border: 1px solid #ccc;
  box-shadow: 2px 2px 6px 0px rgba(0,0,0,0.2);
  border-radius: 20px;
  color: black;
 }

.main-container {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  position: relative;
 }

@media only screen and (max-width: 1039px) {
  .weather-label {
    font-size: 5vw;
    transform: translate(-6vw, 0);
  }
  .content-box {
    padding: 3vh;
    top: 5rem;
    position: absolute;
    max-width: 400px;
    left: 0;
    right: 0;
    margin: 0 auto;
  }
  .toggle-button,
  .weather-line-chart {
    margin-left: auto;
    margin-right: auto;
    position: absolute;
    padding-bottom: 0rem;
    left: 0;
    right: 0;
  }
  .toggle-button {
    width: 30%;
    margin-bottom: 23.5%;
    padding-bottom: 0.5rem;
  }
  
  .weather-line-chart {
    width: 100%;
    top: calc(85% + 2rem);
    height: 100%;
  }
}

@media only screen and (min-width: 1040px) and (max-width: 1805px) {
    .weather-line-chart {
    width: 48%;
  }
}

/*@media only screen and (max-width: 767px) {
  .weather-line-chart {
      width: 400px;
      height: 200px;
  }
}*/

@media only screen and (max-width: 935px) {
  .weather-label {
    font-size: 4.5vw;
    top: 0;
    left: 46.3%;
  }
}

@media only screen and (min-width: 412px) and (max-width: 535px) {
  .weather-label {
    font-size: 5vw;
    top: 0;
    display: grid;
  }
}

@media only screen and (min-width: 935px) and (max-width: 1040px) {
  .weather-label {
    font-size: 4.5vw;
    top: 0;
    left: 46.3%;
  }
}
export default App;


wmo.js(天气解释代码):

const wmo = {
    0:'Clear Sky',
    1:'Mainly Clear',
    2:'Partly Cloudy',
    3:'Overcast',
    45:'Fog',
    48:'Depositing Rime Fog',
    51:"Light Drizzle",
    53:"Moderate Drizzle",
    55:"Intense Drizzle",
    56:"Light Freezing Drizzle",
    57:"Intense Freezing Drizzle",
    61:"Light Rain",
    63:"Moderate Rain",
    65:"Heavy Rain",
    66:"Light Freezing Rain",
    67:"Heavy Freezing Rain",
    71:"Light Snow Fall",
    73:"Moderate Snow Fall",
    75:"Heavy Snow Fall", 
    77:"Snow Grains",
    80:"Light Rain Showers",
    81:"Moderate Rain Showers",
    82:"Heavy Rain Showers",
    85:"Light Snow Showers",
    86:"Heavy Snow Showers",
    95:"Slight Thunderstorm" ,
    951:"Moderate Thunderstorm", 
    96:"Thunderstorm With Light Hail",
    99:"Thunderstorm With Heavy Hail"
  }

  export default wmo;

wz1wpwve

wz1wpwve1#

你可以使用一个循环来添加每个卡片的天气。所有4个数组的长度将是相同的,然后我们可以将一个数组作为引用,同时使用index遍历所有数组。

{weather?.daily?.time.length > 0 ? (
  <>
    <div className="weather-line-chart" id="weather-chart"></div>
    <button
      className="toggle-button"
      onClick={() => setIsFahrenheit((prev) => !prev)}
    >
      Toggle Temperature Unit
    </button>
    <div>
      <div className="weather-forecast">
        {weather.daily.time.map((timeValue, index) => (
          <div className="card" key={timeValue}>
            <h3>{timeValue}</h3>
            <p>Temperature: {weather.daily.temperature_2m_min[index]}</p>
            <p>Weather: {wmo[weather.daily.weather_code[index]]}</p>
          </div>
        ))}
      </div>
    </div>
  </>
) : null}

字符串

相关问题