3

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]
        }
    ]
};
Liam
  • 27,717
  • 28
  • 128
  • 190
Max Rose-Collins
  • 1,904
  • 5
  • 26
  • 45

1 Answers1

1

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:...});   
}
Liam
  • 27,717
  • 28
  • 128
  • 190