I’m learning how the v-for
loops work in Vue. Really liking the idea that I can run the loop directly in my template HTML
but unsure how to properly use the v-for loop to delve into a multi level array.
I have variable called playerDataList
it contains some JSON data. A sample of which is below
JavaScript
x
77
77
1
"stats" : [ {
2
"type" : {
3
"displayName" : "yearByYear",
4
"gameType" : null
5
},
6
"splits" : [ {
7
"season" : "20052006",
8
"stat" : {
9
"assists" : 43,
10
"goals" : 49,
11
"pim" : 82,
12
"games" : 62,
13
"penaltyMinutes" : "82",
14
"faceOffPct" : 0.0,
15
"points" : 92
16
},
17
"team" : {
18
"name" : "Lon. Jr. Knights",
19
"link" : "/api/v1/teams/null"
20
},
21
"league" : {
22
"name" : "Minor-ON",
23
"link" : "/api/v1/league/null"
24
},
25
"sequenceNumber" : 1
26
}, {
27
"season" : "20062007",
28
"stat" : {
29
"assists" : 15,
30
"goals" : 7,
31
"pim" : 30,
32
"games" : 62,
33
"powerPlayGoals" : 0,
34
"penaltyMinutes" : "30",
35
"faceOffPct" : 0.0,
36
"shortHandedGoals" : 0,
37
"plusMinus" : 11,
38
"points" : 22
39
},
40
"team" : {
41
"id" : 1874,
42
"name" : "Kitchener",
43
"link" : "/api/v1/teams/1874"
44
},
45
"league" : {
46
"id" : 141,
47
"name" : "OHL",
48
"link" : "/api/v1/league/141"
49
},
50
"sequenceNumber" : 1
51
}, {
52
"season" : "20072008",
53
"stat" : {
54
"assists" : 40,
55
"goals" : 25,
56
"pim" : 57,
57
"games" : 68,
58
"powerPlayGoals" : 10,
59
"penaltyMinutes" : "57",
60
"shortHandedGoals" : 0,
61
"plusMinus" : 9,
62
"points" : 65
63
},
64
"team" : {
65
"id" : 1874,
66
"name" : "Kitchener",
67
"link" : "/api/v1/teams/1874"
68
},
69
"league" : {
70
"id" : 141,
71
"name" : "OHL",
72
"link" : "/api/v1/league/141"
73
},
74
"sequenceNumber" : 1
75
}
76
}]
77
I’ve got this code so far, and it works to display my content, but it’s only pulling me the first instance. It’s not actually looping and giving me each occurrence.
JavaScript
1
20
20
1
<div class="player-stats-card-inner">
2
<p class="close" v-on:click='showPlayers = !showPlayers'>Close</p>
3
<table>
4
<th>
5
<td>Goals</td>
6
<td>Assists</td>
7
</th>
8
9
<!-- Loop through the JSON data -->
10
<tr v-for="stats in playerDataList.stats" :key="stats.id">
11
<td>
12
{{stats.splits[0].stat.goals}}
13
</td>
14
<td>
15
{{stats.splits[0].stat.assists}}
16
</td>
17
</tr>
18
</table>
19
</div>
20
Is there anything I could do differently to get this properly looping?
Advertisement
Answer
You need to loop the inner properties of stat
. It is not an array.
JavaScript
1
7
1
<tr v-for="stats in playerDataList.stats" :key="stats.id">
2
<td v-for='(value, name) of stats.splits[0].stat'>
3
{{name}} : {{value}}
4
</td>
5
</tr>
6
7