0
我有一個被格式化,像這樣一個本地JSON對象:如何使用嵌套的JSON對象數據作爲數據表列的源?
var rosterdata = {
"homeQBs": ["Ryan Mallet", "Joe Flacco"],
"homeRBs": ["Bobby Rainey", "Terrance West", "Alex Collins", "Javorius Allen"],
"homeWRs": ["Mike Wallace", "Chris Matthews", "Jeremy Maclin", "Griff Whalen", "Breshad Perriman"],
"homeTEs": ["Nick Boyle", "Gavin Escobar", "Maxx Williams", "Benjamin Watson"],
"awayQBs": ["Matt Moore", "Jay Cutler", "David Fales"],
"awayRBs": ["Senorise Perry", "Damien Williams", "Kenyan Drake", "Jay Ajayi"],
"awayWRs": ["Kenny Stills", "Leonte Carroo", "Jakeem Grant", "DeVante Parker", "Jarvis Landry"],
"awayTEs": ["Anthony Fasano", "MarQueis Gray", "Julius Thomas"]
}
請注意數組長度不相等。
我想在一個表中顯示的數據,像這樣:
see example of how first row should look
我無法弄清楚如何讓每列中的數據,而所有嵌套對象的例子我見過方便的同質集合。
這是我目前的嘗試:
<script>
$(document).ready(function() {
var rosterdata = {
"homeQBs": [],
"homeRBs": [],
"homeWRs": [],
"homeTEs": [],
"awayQBs": [],
"awayRBs": [],
"awayWRs": [],
"awayTEs": []
}
{% for player in match_data.home.players %}
{% if player.position == 'QB' %}
rosterdata.homeQBs.push("{{ player.name }}");
console.log("home QB added:" + '{{player.name}}');
console.log(rosterdata);
{% endif %}
{% if player.position == 'RB' %}
rosterdata.homeRBs.push("{{ player.name }}");
{% endif %}
{% if player.position == 'WR' %}
rosterdata.homeWRs.push("{{ player.name }}");
{% endif %}
{% if player.position == 'TE' %}
rosterdata.homeTEs.push("{{ player.name }}");
{% endif %}
{% endfor %}
{% for player in match_data.away.players %}
{% if player.position == 'QB' %}
rosterdata.awayQBs.push("{{ player.name }}");
{% endif %}
{% if player.position == 'RB' %}
rosterdata.awayRBs.push("{{ player.name }}");
{% endif %}
{% if player.position == 'WR' %}
rosterdata.awayWRs.push("{{ player.name }}");
{% endif %}
{% if player.position == 'TE' %}
rosterdata.awayTEs.push("{{ player.name }}");
{% endif %}
{% endfor %}
$('#teamsroster').DataTable({
data: rosterdata,
columns: [
{ data: "homeQBs[]" },
{ data: "homeRBs" },
{ data: "homeWRs" },
{ data: "homeTEs" },
{ data: "awayQBs" },
{ data: "awayRBs" },
{ data: "awayWRs" },
{ data: "awayTEs" }
],
select: {
style: 'single',
items: 'cell'
},
paging: false,
searching: false,
ordering: false,
});
});
//console.log(window.rosterdata);
</script>
和HTML:
<table id="teamsroster" class="table table-bordered w-100" cellspacing="0" width="100%">
<thead>
<tr>
<th>QB</th>
<th>RB</th>
<th>WR</th>
<th>TE</th>
<th>QB</th>
<th>RB</th>
<th>WR</th>
<th>TE</th>
</tr>
</thead>
</table>
提前感謝非常感謝!