Google Line Chart Adding Array of Objects

2020-05-01 07:45发布

问题:

I have an array of objects which I've created by parsing a JSON string:

    var measurementData = @Html.Raw(JsonConvert.SerializeObject(this.Model.Item1));
    var stringifiedData = JSON.stringify(measurementData);
    var parsedData = JSON.parse(stringifiedData);

This gives me a number of objects, depending on the model, looking like this:

Now my question is, how do I add these to a Google line chart without having to hardcode it into the datatable?

This is what I've got now, which works somewhat:

        var data = new google.visualization.DataTable();
        data.addColumn('string', 'TimeStamp');
        data.addColumn('number', selectedMeasurements);

        data.addRows([
            [parsedData[index[0]].TimeStamp, parsedData[index[0]][selectedMeasurements]],
            [parsedData[index[1]].TimeStamp, parsedData[index[1]][selectedMeasurements]]
        ]);

        chart.draw(data, options, {
            isStacked: true,
            vAxis: {
                viewWindowMode: 'explicit',
                viewWindow: {
                    max: 100,
                    min: 0
                }
            }
        });

Here I'm adding two arrays with data to the datatable, since there is two objects to add. But what if I only have one? Or 10? I imagine some kind of foreach inside the .addRows but I'm not sure how to accomplish this.

Any help appreciated!

回答1:

You can use "setValue(rowIndex, columnIndex, value)" method:

var jsonData = '[{"SlideId":"D2011", "InstrumentId":"I335", "IncMin":"37.13", "IncMax": "37.19", "BrMin":"31.4"}, {"SlideId":"D2014", "InstrumentId":"I335", "IncMin":"37.13", "IncMax": "37.19", "BrMin":"31.4"}]';

var parsedData = JSON.parse(jsonData);
var len = parsedData.length;

var data = new google.visualization.DataTable();
data.addColumn('string', 'TimeStamp');
data.addColumn('number', selectedMeasurements);

data.addRows(len);

for (var n = 0; n < len; n++) {
    var i=0;
    for (var key in parsedData[n]) {
        data.setValue(n, i, parsedData[n][key]);
        i++;
    }
}

chart.draw(data, options, {
        isStacked: true,
        vAxis: {
            viewWindowMode: 'explicit',
            viewWindow: {
                max: 100,
                min: 0
            }
        }
});

http://jsfiddle.net/mblenton/qnusuLtn/2/