简体   繁体   中英

Accessing nested JSON object in React

Dataset: https://disease.sh/v3/covid-19/historical/usa?lastdays=all

I am newer to React and am trying to get my feet wet with a COVID-19 Tracker so bear with me... I am trying to access Timeline > Cases from the above dataset but can't seem to make it work. I've tried let date in data.timeline.cases however that doesn't work either. Maybe i'm looking in the wrong spot - looking for some guidance. Thanks!

const buildChartData = (data, casesType) => {
  let chartData = [];
  let lastDataPoint;

  for (let date in data.cases) {
    if (lastDataPoint) {
      let newDataPoint = {
        x: date,
        y: data[casesType][date] - lastDataPoint,
      }
      chartData.push(newDataPoint);
    }
    lastDataPoint = data[casesType][date];
  }
  return chartData;
};

function LineGraph({ casesType = 'cases' }) {
  const [data, setData] = useState({});

  useEffect(() => {
    const fetchData = async() => {
      await fetch('https://disease.sh/v3/covid-19/historical/usa?lastdays=120')
        .then((response) => {
          return response.json()
        })
        .then(data => {
          let chartData = buildChartData(data, casesType);
          setData(chartData);
        });
    };
    
    fetchData();
  }, [casesType]);

Ok, as you said you tried with let date in data.timeline.cases but you need to change the other part of code too.

It s not data[casesType] but data.timeline[casesType]

  for (let date in data.timeline.cases) {
    if (lastDataPoint) {
      let newDataPoint = {
        x: date,
        y: data.timeline[casesType][date] - lastDataPoint,
      }
      chartData.push(newDataPoint);
    }
    lastDataPoint = data.timeline[casesType][date];
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM