我试图使用Chart.js来显示未知的JSON数据(我做知道的数据的唯一部分是它将包含" time")
我有几个数据集,所以我如何从这些格式中获取数据......:
数据集1:
dataset1 = [ { "time": "2017-03-02 09:00", "volts": 10, "amps": 4.5 },{ "time": "2017-03-02 09:10", "volts": 9.87, "amps": 4.15 }, ...]
数据集2:
dataset2 = [ { "level": 1.23, "time": "2017-03-02 09:00", "volts": 3.5 }, { "level": 1.56, "time": "2017-03-02 09:10", "volts": 3.6 }, ...]
...以此格式(对于dataset1):
data[ "time" ] = [ "2017-03-02 09:00", "2017-03-02 09:10", ...]
data[ "volts" ] = [ 10, 9.87 ...]
data[ "amps" ] = [ 4.5, 4.15 ...]
...或此格式(对于dataset2):
data[ "time" ] = [ "2017-03-02 09:00", "2017-03-02 09:10", ...]
data[ "level" ] = [ 1.23, 1.56 ...]
data[ "volts" ] = [ 3.5, 3.6 ...]
我事先不知道键(例如伏特,放大器,电平)是什么,所以我无法宣布任何阵列进入。
我希望有人可以提供帮助。
答案 0 :(得分:0)
您可以使用一些动态数组实现此目的:
var dataset1 = [ { "time": "2017-03-02 09:00", "volts": 10, "amps": 4.5 },{ "time": "2017-03-02 09:10", "volts": 9.87, "amps": 4.15 }];
var dataset2 = [ { "level": 1.23, "time": "2017-03-02 09:00", "volts": 3.5 }, { "level": 1.56, "time": "2017-03-02 09:10", "volts": 3.6 }];
var data = [];
var datasets = [dataset1,dataset2];
for (var i in datasets) {
var dataset = datasets[i];
for (var j in dataset) {
var d = dataset[j];
for (var k in d) {
if (!data[k]) data[k] = [];
data[k].push(d[k]);
}
}
}