Chartjs-Looping through json array properties

1๐Ÿ‘

โœ…

If you replace measurement with data.Series and get rid of the hasOwnProperty(measurement) thing, you are almost there. The only thing you need is a way to keep the transformation from a list of {Date, Value} objects to a pair of list of dates and value for each serie.

var series = {};
// This loop is looping across all the series.
// x will have all the series names (heights, lengths, etc.).
for (var x in data.Series) {
  var dates = [];
  var values = [];
  // Loop across all the measurements for every serie.
  for (var i = 0; i < data.Series[x].length; i++) {
    var obj = data.Series[x][i];
    // Assuming that all the different series (heights, lengths, etc.) have the same two Date, Value attributes.
    dates.push(obj.Date);
    values.push(obj.Value);
  }
  // Keep the list of dates and values by serie name.
  series[x] = {
    dates: dates,
    values: values
  };
}

series will contain this:

{
    heights: {
        dates: [
            '2014-10-01',
            '2014-10-01',
            '2014-10-01'
        ],
        values: [
            22,
            53,
            57
        ]
    },
    lengths: {
        dates: [
            '2014-10-01',
            '2014-10-01'
        ],
        values: [
            54,
            33
        ]
    }
}

So you can use them like this:

console.log(series);
console.log(series.heights);
console.log(series.heights.dates);
console.log(series.heights.values);
console.log(series.lengths);
console.log(series.lengths.dates);
console.log(series.lengths.values);

Leave a comment