Alan Power Alan Power - 11 days ago 7
JSON Question

Angular - building JSON dynamically for use with chartist

I have an ionic project and am using the following library:
http://gionkunz.github.io/chartist-js/index.html

Actually draing the chart is achieved with the following:

var chart = new Chartist.Line('.ct-chart', {
series: [
{
name: 'series-1',
data: [
{x: new Date(143134652600), y: 53},
{x: new Date(143234652600), y: 40},
{x: new Date(143340052600), y: 45},
{x: new Date(143366652600), y: 40},
{x: new Date(143410652600), y: 20},
{x: new Date(143508652600), y: 32},
{x: new Date(143569652600), y: 18},
{x: new Date(143579652600), y: 11}
]
},
{
name: 'series-2',
data: [
{x: new Date(143134652600), y: 53},
{x: new Date(143234652600), y: 35},
{x: new Date(143334652600), y: 30},
{x: new Date(143384652600), y: 30},
{x: new Date(143568652600), y: 10}
]
}
]
}, {
axisX: {
type: Chartist.FixedScaleAxis,
divisor: 5,
labelInterpolationFnc: function(value) {
return moment(value).format('MMM D');
}
}
});


With a DIV:

<div class="ct-chart ct-perfect-fourth"></div>


Instead however of having a hardcoded array for the series as shown above, I would like to build this dynamically through a function call.

Any example of how I might do that?

Thanks!

Answer

This is a rough example; you could replace the input series1, series2 with an array of arrays and make the lower for-loops two wrapped loops to handle multiple series. This would also entail adding the objects to the series array in the outer loop.

For now, try something like this:

function generateJSON(series1, series2) {
  var chartInternal = {
    series: [
      {
      name: 'series-1',
      data: []
      },
      {
      name: 'series-2',
      data: []
      }
      ]
    }, {
      axisX: {
        type: Chartist.FixedScaleAxis,
        divisor: 5,
        labelInterpolationFnc: function(value) {
          return moment(value).format('MMM D');
        }
      }
    };

  for (var i = 0, len = series1.length; i < len; i++) {
    chartInternal.series[0].data.push({x: new Date(series1[i].date), y: series1[i].y});
  }
  for (var i = 0, len = series2.length; i < len; i++) {
    chartInternal.series[1].data.push({x: new Date(series2[i].date), y: series2[i].y});
  }
  return chartInternal;
}

Usage:

var series1 = [
  { date: 1234567, y:52 },
  ... more
];
var series2 = [
  { date: 7654321, y:52 },
  ... more
];
var chart = new Chartist.Line('.ct-chart', generateJSON(series1, series2))
Comments