Home > Net >  chart js using for loop
chart js using for loop

Time:04-09

HMTL Code:

<div >
    <div >
        <div >
            <h6 >Evolution of Names vs Dates</h6>
            <div >
            </div>
        </div>
        <div >
            <div >
                <canvas id="food_items_line_chart"></canvas>
            </div>
        </div>
    </div>
</div>

Javascript Code:

<script>
 $(document).ready(function () {

  var ctx = $("#my_line_chart");

  var names2 = ['name1', 'name2'];

  var colors2 = ['orange', 'blue'];

  var data2 = [[10,20],[20,30]];

  var dates2 = ['2020-01', '2020-02'];

  var data =
  {
    labels: dates2,
    datasets :
    [
        for (let i = 0; i <= data.length; i  )
        {
            {
                label: names2[i],
                data: data2[i],
                borderColor:
                [
                colors2[i],
                ],
                borderWidth : 1
            },
        }
    ]
  };

  var options = {
    title : {
      display : false,
      position : "top",
      fontSize : 18,
      fontColor : "#111"
    },
    legend : {
      display : true
    },
    scales : {
      yAxes : [{
        ticks : {
          min : 0
        }
      }]
    }
  };

  var chart = new Chart( ctx, {
    type : "line",
    data : data,
    options : options
  });
});
</script>

I am just starting to learn javascript so I'm probably doing alot of things wrong, but the idea is to load this ChartJs Line chart on a HTML page. I am getting alot of errors while inspecting the HTML page, the first error is: "Uncaught SyntaxError: Unexpected token 'for'".

CodePudding user response:

You can use Array.map() to directly transform your data into the definition required by Chart.js.

Please take a look at your amended and runnable code and see how it works.

var names2 = ['name1', 'name2'];
var colors2 = ['orange', 'blue'];
var data2 = [[10, 20], [20, 30]];
var dates2 = ['2020-01', '2020-02'];

new Chart('food_items_line_chart', {
  type: 'line',  
  data: {
    labels: dates2,  
    datasets: dates2.map((ds, i) => ({
      label: names2[i],
      data: data2[i],
      borderColor: colors2[i],
      borderWidth: 1
    }))  
  },
  options:  {
    scales: {
      y: {
        min: 0        
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js"></script>
<canvas id="food_items_line_chart" height="80"></canvas>

  • Related