0

I have a for loop that gets data that I'm trying to parse into a chart. I can only seem to get the first bit of data, not everything in the array.

My JS file -

   for (i = 0; i < results; i++) {
       const assetName = await tronWeb.trx.getTokenByID(str.assetV2[i]['key']);
       var getAsset = JSON.stringify(assetName);
       var name = JSON.parse(getAsset);
       var assetValueRaw = str.assetV2[i]['value'] / 100;
       var assetValue = assetValueRaw.toLocaleString()

       // get chart data from for loop
       chartData = [name.abbr, assetValueRaw];
   }



   anychart.onDocumentReady(function () {

      // create pie chart with passed data from for loop
      var chart = anychart.pie([chartData]);

      var palette = anychart.palettes.rangeColors();
      palette.items([{ color: '#64b5f6' }, { color: '#455a64' }]);
      chart.background().fill("#222E3A 0.0");
      chart.height('100%');
      chart.width('100%');
      chart.padding(80);
      chart
         .innerRadius('95%')
         .palette(palette);
      chart.container('container');
    chart.draw();
  });

Example data:

chartData = [['test', 477], ['test2 ', 1000],];

The chart populates but there is supposed to be 3 values but only returns 1. How can I get the loop to push all 3 data values to the chartData variable?

1 Answer 1

1

You are reassigning a new array to chartData on each iteration, so it ends up with only the last value. Instead, you should create an empty array before the loop and push elements into it.

let chartData = [];
for (i = 0; i < results; i++) {
       const assetName = await tronWeb.trx.getTokenByID(str.assetV2[i]['key']);
       var getAsset = JSON.stringify(assetName);
       var name = JSON.parse(getAsset);
       var assetValueRaw = str.assetV2[i]['value'] / 100;
       var assetValue = assetValueRaw.toLocaleString()

       // get chart data from for loop
       chartData.push([name.abbr, assetValueRaw]);
   }
//...
var chart = anychart.pie(chartData);
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you, makes sense but Im not getting the chart now, I get the first valued displayed but I must be preparing the chartData wrong?
@RyanD What should the result look like?
chartData = [['test', 477], ['test2 ', 1000], ['test3 ', 1000]];
@RyanD Try anychart.pie(chartData); (removed square brackets)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.