Home > Blockchain >  How to access one element in a object json array and bind this data on the X-axis in Ionic 6 / Chart
How to access one element in a object json array and bind this data on the X-axis in Ionic 6 / Chart

Time:03-14

I following a tutorial how to use ChartJS in ionic 6. I have a json response like this:

[
    {
        "id": "1",       
        "name": "Fruit",
        "last_updated": "2022-03-13T20:13:12.322Z"
    }
]

I only want to have the "last_updated" in my response and convert this to an array and bind it to the X-axis in a chart with the framework ChartJS.

This is my code to get the element and convert it to an array:

getLastUpdated() {
    var json;
    this.http.get(httpurl)
      .subscribe(data => {
        json = data;
        var datarray = [];
        for (var i of json.data) {
          datarray.push(i.last_updated)
          console.log(datarray);
        }

      })
  }

Then I call this method via a service like this:

this.dataService.getLastUpdated();

Bind this data like this:

lineChartMethod() {
    this.lineChart = new Chart(this.lineCanvas.nativeElement, {
      type: 'line',
      data: {
        labels: dataarray,
        datasets: [
          {
            label: 'Test',
            data: [65, 59, 80, 81, 56, 55, 40, 10, 5, 50, 10, 15],

          }
        ]
      }
    });
  }

And in my HTML page I render the chart like this:

 <canvas #lineCanvas></canvas>

I get an error like this in my console:

ERROR TypeError: json.data is not iterable

Can someone point me in the right direction?

CodePudding user response:

for (var i of json.data) {
// ...

// Should become:

for (var i of json) {
// ...
  • Related