Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chart.js plotting two json datasets on a line chart

I'm trying to work out how to plot labels to the correct places using Chart.js

var json = {
    "competition one": [
        {
            "date": "2015-05-20",
            "position": 37
        },
        {
            "date": "2015-05-21",
            "position": 22
        }
    ],
    "competition two": [
        {
            "date": "2015-05-20",
            "position": 29
        },
        {
        "date": "2015-05-21",
        "position": 19
        }
    ]
}

How can I plot the labels to the correct places? With the dates going to the correct labels so it isn't repeated?

Specifically, I'm struggling to get "competition one" into the label of the dataset array (label: "competition one")

I need it to resemble the following data structure that is required by Chart.js?

var data = {
    labels: ["2015-05-20", "2015-05-21"],
    datasets: [
        {
            label: "competition one",
            data: [37, 22]
        },
        {
            label: "Competition two",
            data: [29, 19]
        }
    ]
};
like image 501
Max Rose-Collins Avatar asked Jan 24 '26 22:01

Max Rose-Collins


1 Answers

As mentioned in comments you can get the properties names like thus:

var json = {
    "competition one": [
        {
            "date": "2015-05-20",
            "position": 37
        },
        {
            "date": "2015-05-21",
            "position": 22
        }
    ],
    "competition two": [
        {
            "date": "2015-05-20",
            "position": 29
        },
        {
        "date": "2015-05-21",
        "position": 19
        }
    ]
}

var keys = Object.keys(json);
for (var i = 0; i < keys.length; i++)
{
    var key = keys[i];
    //"competition one", "competition two", etc
    console.log(key);   
}

Fiddle

you then just need to manipulate these values into your desired object structure.

var keys = Object.keys(json);
//set up our object containing an array called datasets
var data = {datasets:[]};
for (var i = 0; i < keys.length; i++)
{
    var key = keys[i];
    //push the key into the dataset array as an object {}
    data.datasets.push({label:key, data:...});   
}
like image 107
Liam Avatar answered Jan 26 '26 12:01

Liam