How to iterate through JSON response from fetch() then add it to chart data?

mismaah :

I'm trying to get a JSON response from an API and then add it to a Chart.js chart. This is the JS code for the Vue component

import LineChart from './LineChart.js'
  export default {
      name: 'Chart',
      components: LineChart,
      data () {
        return {
          loaded: false,
          stockData: {
            labels: null,
            datasets: null
          }
        }
      },
      async mounted () {
        this.loaded = false
        try{
          const response = await fetch('http://localhost/AAPL')
          const stock = await response.json()
          console.log(stock)
          let annual = stock.Earnings.Annual
          for(let i of annual){
            this.stockData.labels.push(i.date)
            this.stockData.datasets.push(i.epsActual)
          }
          this.loaded = true
        } catch (e){
          console.error(e)
        }
      }
  }

But I get the error

Chart.vue?36ee:38 TypeError: annual[Symbol.iterator] is not a function

Is there any other way to add the data to the chart?

Dan :

JavaScript has several types of loops. Most likely annual is an object without a custom iterator, and that's why you're getting this message.

1) for ... of is for looping over iterable objects such as arrays and other array-like structures, or objects that have a custom iterator defined.

2) for ... in is for looping over object keys (and array indexes).

Try to use for ... in instead:

for(let i in annual){
    this.stockData.labels.push(annual[i].date)
    this.stockData.datasets.push(annual[i].epsActual)
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=30018&siteId=1