javascript - 循环遍历对象数组并将其存储在表中[JS]
问题描述
我正在尝试遍历一组对象并将其存储在表格中,这是我的代码正在执行的事件序列。
- 从 JSON 文件中获取值 [完成]
- 将它们作为对象数组存储在我的代码中,例如 so[done]: var results = {name : [], goal: [], assistants: [] , team: []};
3.在我希望格式如下的表格中显示内容:
Name Goals Assists Team
Player 1 Name Player 1 Goals Player 1 Assists Player 1 Team
- 拾取的包含数组的对象如下所示:
{
assists: [4, 2, 2, 9, 1, 7, 3, 6, 4, 6, 3, 1, 2, 7, 3, 1, 18, 3, 10, 9],
goals: [23, 20, 19, 19, 17, 16, 16, 16, 15, 15, 14, 13, 13, 12, 12, 11, 11, 11, 10, 10],
name: ['J. Vardy', 'P. Aubameyang', 'D. Ings', 'Mohamed Salah', 'R. Sterlin', 'S. Mané ', 'S. Agüero', , , , , , , , , , , ,],
team: ['Leicester', 'Arsenal', 'Southampton', 'Liverpool', 'Manchester City', 'Liverpool', 'Manchester City', , , , , , , , , , , ,],
}
- 我的代码示例使用如下的每个功能,但我的结果什么也不显示,下面的完整代码:[进行中]
var stats, table;
var results =
{name : [], goals: [], assists: [] , team: []};
//We need to initiate a request to read the json file
$.getJSON('data/topscores.json')
.done(function(data){ // Once done do the below
$.each(data, function(keyIndex) { //Loop through the JSon, grab all values and store in obj array
results.name[keyIndex] = (data[keyIndex].player.name)
stats = data[keyIndex].statistics
results.goals[keyIndex] = (stats[0].goals.total)
results.assists[keyIndex] = (stats[0].goals.assists)
results.team[keyIndex] = (stats[0].team.name)
});
table = document.getElementById('rank').getElementsByTagName('tbody')[0] //Grabbing first contents of table body
for (var key in results.name.length) {
var row = document.createElement('tr'); //insert 20 rows beginning of the loop
Object.values(res).forEach(text => { //Loop through object array and store values in respective table cells
var cell = document.createElement('td')
var textNode = document.createTextNode(text)
cell.appendChild(textNode)
row.appendChild(cell)
});
table.appendChild(row)
}
}) //End of JSON function
关于如何将对象的结果数组显示到表格单元格中的任何帮助将不胜感激
解决方案
我看到的明显问题是您对 json 结果的迭代。该for-in
循环仅用于迭代对象的属性,并且您想要迭代数组results.name
。
即使您正在迭代一个对象,您的 for 循环语法也没有多大意义(迭代数组的长度?!)。
试试这样:for (let i=0; i<results.name.length; i++)
。
另外,里面有什么res
?Object.values(res)
!
推荐阅读
- csv - 使用 Ansible 解析 CSV
- scala - Scala 如何将案例类转换为函数?
- react-native - 更改活动图像反应原生
- java - 打印输入的长度和单词
- pine-script - PineScript TradingView:超过一年的代码(12 个月 +)
- sql - SSDT Re-alter 什么都没有改变时触发
- javascript - 使用NodeJS,头部的javascript不能使用来自服务器的参数
- android - 在 Android Google 地图中排序图层
- c++ - 将外部头文件导入 VS Code
- sql-server - Sql server 2017 开发人员设置失败,出现空白错误