gpt4 book ai didi

javascript - Chart.js 在折线图上绘制两个 json 数据集

转载 作者:行者123 更新时间:2023-11-29 15:34:48 25 4
gpt4 key购买 nike

我正在尝试研究如何使用 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" 放入 dataset 数组的 label (label: "竞赛一")

我需要它类似于 Chart.js 所需的以下数据结构吗?

var data = {
labels: ["2015-05-20", "2015-05-21"],
datasets: [
{
label: "competition one",
data: [37, 22]
},
{
label: "Competition two",
data: [29, 19]
}
]
};

最佳答案

如评论中所述,您可以获得如下属性名称:

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

然后您只需将这些值操作成您想要的对象结构。

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:...});
}

关于javascript - Chart.js 在折线图上绘制两个 json 数据集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30458607/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com