如何将JSON数据转换为未知名称的数组
问题描述:
我试图使用Chart.js来显示未知的JSON数据(我知道的只有部分数据做它将包含“time”)。如何将JSON数据转换为未知名称的数组
我有几个数据集,所以我如何才能从这些格式的数据... ...:
数据集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 }, ...]
...到此格式(对于数据集1):
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 ...]
我不知道提前哪些键(例如伏特,安培,水平)将会是,所以我无法宣布任何阵列推入。
我希望有人能帮忙。
答
可以使用一些动态数组实现这一点:
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]);
}
}
}
你可以使用[Object.keys()](https://developer.mozilla.org/en/ docs/Web/JavaScript/Reference/Global_Objects/Object/keys)来获取对象所具有的键的列表,但我不知道它是如何被支持的。一个示例调用将会返回'[“time”,“volts”,“amps”]'Object.keys(dataset1 [0])'' – George
@George:我现在来看看。感谢您的迅速反应:-) – simonl
嗯,我不知道Object.keys(或Object.values或Object.entries - 有趣),但我仍然无法看到如何创建数据[xxx]数组: - ( – simonl