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>
提前感谢非常感谢!