我正在请求一个网络服务,它使用这样的CSV文件进行响应(过去几年有更多的月度数据)。对我来说重要的是该行中的第一个和最后一个信息(即日期和值):
2010/01/01,51.67074582499006,13.789093928493081,-0.0010074468085106377
2010/02/01,51.67074582499006,13.789093928493081,0.0024117021276595747
2010/03/01,51.67074582499006,13.789093928493081,0.026550000000000004
2010/04/01,51.67074582499006,13.789093928493081,0.08252659574468087
2010/05/01,51.67074582499006,13.789093928493081,0.12837446808510639
2010/06/01,51.67074582499006,13.789093928493081,0.140618085106383
2010/07/01,51.67074582499006,13.789093928493081,0.0668787234042553
2010/08/01,51.67074582499006,13.789093928493081,0.10335744680851064
2010/09/01,51.67074582499006,13.789093928493081,0.08095000000000001
2010/10/01,51.67074582499006,13.789093928493081,0.0400159574468085
2010/11/01,51.67074582499006,13.789093928493081,0.004214893617021277
2010/12/01,51.67074582499006,13.789093928493081,-0.0018680851063829788
2011/01/01,51.67074582499006,13.789093928493081,0.0011914893617021279
2011/02/01,51.67074582499006,13.789093928493081,0.003752127659574468
2011/03/01,51.67074582499006,13.789093928493081,0.027225531914893623
有了这些信息,我想构建一个Highcharts图形,每个图形显示一个单独的行。它应该如下所示:
我当前的版本将所有数据添加到一个很长的行 - 这很好,但不能使这些年份的值相当:
function processData(allText)
{
var allTextLines = allText.split(/\r\n|\n/);
var lines = []; var n = 0; var data = []; var dateValue = [];
for (var i=1; i<allText.length; i++)
{
if (allTextLines[i])
{
if ((allTextLines[i].substring(0,2) == "19") || (allTextLines[i].substring(0,2) == "20"))
{
dateValue = allTextLines[i].split(",");
// everything will be concatenated into one single line
if(Number.isFinite(parseFloat(dateValue[3])))
{
data[n] = [new Date(dateValue[0]).getTime(), parseFloat(dateValue[3])];
}
n++;
}
}
}
return data;
}
现在,我需要的是一个看起来像这样的结果:
series:
[{
name: "2010",
data: [-0.001007447,0.002411702,0.02655,0.082526596,0.128374468,0.140618085,0.066878723,0.103357447,0.08095,0.040015957,0.004214894,-0.001868085]
},{
name: "2011",
data: [0.001191489,0.003752128,0.027225532,0.090589362,0.129121277,0.141264894,0.119343617,0.113290426,0.093575532,0.044221277,0.015881915,0.004068085]
}
],
...
但我不知道我的Javascript代码必须如何,以产生这样的结果。谁能给我一个提示?
答案 0 :(得分:0)
您可以像这样提取数据:
function extract(csv) {
var rows = csv.split(/\r\n|\n/);
var data;
var series = [];
var serie = {name: -1, data: []};
for (var i = 0; i < rows.length; i++) {
data = rows[i].split(',');
if (serie.name === -1) {
serie.name = data[0].substr(0,4);
}
else if (serie.name !== data[0].substr(0,4)) {
series.push(serie);
serie = {name: data[0].substr(0,4), data: []};
}
serie.data.push(parseFloat(data[3]));
}
series.push(serie);
return series;
}
jsFiddle:https://jsfiddle.net/mk7x7bbe/