【发布时间】:2016-02-02 13:20:35
【问题描述】:
对于 highcharts,我需要生成解析数据以生成系列。 API 中的数据如下所示:
[ date : XX,
series : [
player_id : 1,
team_id : 1,
score : 4 ],
[
player_id : 2,
team_id : 4,
score : 1 ],
[
player_id : 4,
team_id : 1,
score : 4 ]
],
[ date : XX+1
series : ...
],
...
首先,用户必须选择球队和球员,但有时没有结果。例如,对于日期 XX,我选择了 4 个团队 ID,但 API 仅返回其中 2 个。我必须考虑到这一点。 我正在尝试不同类型的系列,第一个代表所有球队的得分,第二个代表所有球员的得分,另一个代表每个球队的得分。所以有很多图。
我使用的是 Ampserand.js,模型相同,但他被调用的时间与表单中选择的团队数量一样多。
我做了这样的事情:
function parse(data) {
var series = [];
var dates = [];
var findIndexByValue = function(arraytosearch, key, valuetosearch) {
for (var i = 0; i < arraytosearch.length; i++) {
if (arraytosearch[i][key] == valuetosearch) {
return i;
}
}
return null;
}
for (var i = 0; i < data.length; i++) {
var dTemp = new Date(data[i].date).getTime();
// Keep dates in case of empty values
dates.push(dTemp);
for (var s = 0; s < data[i].series.length; s++) {
var current = data[i].series[s];
if (this.currentype === "allTeamSeries") {
var currentIndex = findIndexByValue(series, "team", current.team_id);
if (currentIndex === null) {
series.push({
team: current.team_id,
data: [dTemp, current.avg]
});
} else {
series[currentIndex].data.push([dTemp, current.score]);
}
} else if (this.currentResource === "playerseries") {
var currentIndex = findIndexByValue(series, "player", current.player_id);
if (currentIndex === null) {
series.push({
player: current.player_id,
data: [dTemp, current.score]
});
} else {
series[currentIndex].data.push([dTemp, current.score]);
}
} else { //currentTeam from model
if (this.currentTeam === current.team_id) {
var currentIndex = findIndexByValue(series, "site", current.site_id);
if (currentIndex === null) {
series.push({
team: current.team_id,
data: [dTemp, current.score]
});
} else {
series[currentIndex].data.push([dTemp, current.score]);
}
}
}
}
}
// Avoid empty charts
if (series.length === 0) {
series.push({
team: this.currentTeam,
data: []
});
dates.forEach(function(elem) {
series[0].data.push([elem, 0]);
});
}
return {
startdate: this.config.startdate,
enddate: this.config.enddate,
series: series
};
}
当 api 的结果中没有团队的结果时生成的系列有问题。
一个可用的数组应该是这样的:
series: [{
name: 'Team 1',
data: [4163, 5203, 6276, 5408, 3547, 3729, 3828,4163, 5203, 6276, 5408, 3547, 3729, 3828,4163, 5203, 6276, 5408, 3547, 3729, 3828]
},
{
name: 'Team 2',
data: [...]
}]
此外,代码看起来很多余,是否有一些 Array 函数的技巧可以更轻松地做到这一点?
在此先感谢,这对我来说是个大问题!
【问题讨论】:
标签: javascript arrays highcharts ampersand.js