【发布时间】:2017-12-15 16:05:20
【问题描述】:
我有一个原始 JSON 文件,看起来像 this。其中,它包含 18 个对象,每个对象都包含有关特定英超足球周的信息。在这 18 个比赛周信息对象中的每一个中,它都包含 20 个关于球队的对象,包括他们的位置、目标等。看起来是这样的:nested structure of my JSON.
我想从中获得的相关信息是团队及其当周的相关职位。如此有效,我想要每周 18 次排行榜的快照。但是,我需要的信息格式必须看起来像 this。也就是说,它需要是一个数组数组,其中每个数组,它包含球队的名字,然后是每周的联赛位置,用逗号分隔。图中只有第一周的联赛位置,但我需要每周的位置,所以数组中的每个数组对象应该是17个项目。
我已经尝试了很长时间将信息从第一种形式获取到第二种形式(即从嵌套的 JSON 到数组数组),但我似乎无法以正确的方式操作数据.我试过排序函数和嵌套循环,但我似乎做不到。
这就是我的代码当前的样子(使用 d3.js 库来加载获取请求)。
<script>
var count = 21
var requests = new Array()
//This generates an array of get requests
for (i=1; i<count; i++) {
requests[i] = d3.request("http://api.football-data.org/v1/competitions/445/leagueTable/?matchday=" + i)
.header("X-Auth-Token", "")
}
var q = d3.queue();
//This uses the d3 queue function to make 16 get requests for the data, and
//then once all the data is retrieved (awaitAll), it excutes the callback function
for (i=1; i<count; i++) {
q.defer(requests[i].get);
}
q.awaitAll(function(error, files) {
if (error) throw error;
//This converts the retrieved files to a JSON
var Matchdays = new Array()
for(i=0; i<count-1; i++) {
Matchdays[i] = files[i].response
Matchdays[i] = JSON.parse(Matchdays[i])
}
console.log(Matchdays)
//This makes a table in the required format for Week 1. I need all the other Weeks
// to follow the numbers that are already there, however.
var Week1Table = new Array()
for(i=0; i<count-1; i++) {
Week1Table[i]= [Matchdays[0].standing[i].teamName, Matchdays[0].standing[i].position]
}
console.log(Week1Table)
})
</script>
【问题讨论】:
-
所以这个 'Week1Table[i]= [Matchdays[0].standing[i].teamName, Matchdays[0].standing[i].position]' 你到底想要什么,但是每个 MatchDay?
-
嗯,有点。我实际上希望它看起来像,例如,Week1Table[0] = ["Manchester United FC", 1, 2, 2, 3, 4, 5...],其中的数字是每个相关球队的联赛排名连续一周。麻烦的是,在原始 JSON 中,每个 matchday 对象都让球队每周都在位置上移动,如果你明白我的意思的话。
-
我有点好奇为什么需要转换数据。它的交付方式似乎更容易使用,特别是如果您正在使用 d3 构建一些东西......
-
我实际上使用的是 c3.js,它需要非常特定形式的数据。我还没有完全学会如何使用 d3。不过谢谢!
标签: javascript arrays json sorting d3.js