我正在尝试使用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
}
]
}
如何将标签绘制到正确的位置?日期是否正确的标签,所以不重复?
具体来说,我很难将"competition one"
加入label
数组的dataset
(label: "competition one"
)
我需要它类似于Chart.js所需的以下数据结构吗?
var data = {
labels: ["2015-05-20", "2015-05-21"],
datasets: [
{
label: "competition one",
data: [37, 22]
},
{
label: "Competition two",
data: [29, 19]
}
]
};
答案 0 :(得分:1)
如评论中所述,您可以获得如下属性名称:
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);
}
然后您只需要将这些值操作到您想要的对象结构中。
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:...});
}