我正在使用 ApexCharts 来显示数据库中的数据,它工作得非常好,直到我必须创建多个数据系列。我以这样的多个数组的形式获取数据(注意:我没有得到水果列表,这是为了举例)
var fruits = ["apple","apple","apple","apple","apple"]; // Name of the fruit
var dates = ["2019-04-01","2019-04-02","2019-04-03","2019-04-04","2019-04-05"];
var values = [14,9,17,5,11];
fruits[0] 与 dates[0] 和 values[0] 一起使用(将它们视为数据库中的行)。
在这种情况下,我只有一个数据系列要传递给 ApexCharts,我可以这样做:
var matchedData = [];
// I create nested arrays in matchedData, each array corresponding to a tuple, like so : matched[0] = [dates[0],values[0]]
for(let i = 0; i < fruits.length; i++) {
date = new Date(dates[i]); // To transform the date string to Javascript timestamp
matchedData[i] = [date.getTime(),values[i]];
}
var options = {
chart: {
type: 'line'
},
series: [{
label: "Data",
data: matchedData
}],
xaxis: {
type: 'datetime'
},
}
var chart = new ApexCharts(document.getElementById('chart'), options);
chart.render();
但它仅在“fruits”数组仅包含一种水果而不包含不同种类时才有效。所以如果我的数组是这样的:
var fruits = ["apple","banana","apple","banana","strawberry"];
var dates = ["2019-04-01","2019-04-02","2019-04-03","2019-04-04","2019-04-05"];
var values = [14,9,17,5,11];
我必须动态创建 3 个以水果命名的数组(因此在本例中为“苹果”、“香蕉”和“草莓”),每个数组都包含相应的日期和值。每个数组看起来像这样:
apple = [
["2019-04-01", 14], // I wrote the time in string for readability here but in reality it would be written in the JavaScript timestamp format
["2019-04-03", 17]
];
banana = [
["2019-04-02", 9],
["2019-04-04", 5]
];
strawberry = [
["2019-04-05",11]
];
这些数据系列将像这样传递给 ApexCharts:
var options = {
chart: {
type: 'line'
},
series: [
{
label: "apple",
data: apple
},{
label: "banana",
data: banana
},{
label: "strawberry",
data: strawberry
}
],
xaxis: {
type: 'datetime'
},
}
var chart = new ApexCharts(document.getElementById('chart'), options);
chart.render();
我的问题如下:
我不知道在运行之前我需要创建多少个系列,我不知道它们的名字,也不知道如何动态地将它们传递给 ApexCharts(如果有 N 个系列,我需要 N {label /data} 子句)。
我已经开始为每个水果动态创建一个数组,它看起来像这样:
for(let i = 0; i < fruits.length; i++) {
if(fruits[i] in window) {
date = new Date(dates[i]);
window[fruits[i]].push([date.getTime(),values[i]]);
} else {
window[lines[i]] = [];
date = new Date(dates[i]);
window[lines[i]].push([date.getTime(),values[i]]);
}
}
然后我可以稍后访问每个数组,但前提是已经知道“fruits”数组中的不同值。