使用数据(Json),为数组中的每个对象创建新的元素,行和列 [英] Use data (Json), create new element, row and columns for each object in array
问题描述
我是JavaScript新手.我们应该从这里获取数据: https://stryk.herokuapp.com/tipset 然后使用数据,为每个游戏创建一个新的行( tr
),其中包含列( td
)(我无法更改HTML文件中的任何内容).它看起来应该像这样 https://i.stack.imgur.com/3ejGx.png
I'm new at JavaScript.
We are supposed to get data from here: https://stryk.herokuapp.com/tipset
then use the data, creating a new row (tr
) with columns (td
) for each game (I can't change anything in the HTML file). It supposes to look something like this https://i.stack.imgur.com/3ejGx.png
我不知道如何遍历数据然后使用它.
I can't figure out how to loop through the data and then use it.
import {getData} from './getdata.js';
let data = getData();
event();
function createTR(text) {
var x = document.createElement("TR");
x.setAttribute("class", "myTr");
document.getElementById("table").appendChild(x);
var y = document.createElement("TD");
var t = document.createTextNode(text);
y.appendChild(t);
document.querySelector(".myTr").appendChild(y);
}
function event() {
document.querySelector('#active').addEventListener('click', myFunction);
}
function myFunction() {
data.then(createTR);
}
export function getData() {
return fetch('https://stryk.herokuapp.com/tipset')
.then(function (response) {
return response.json();
})
.then(function (data) {
console.dir(data);
});
}
推荐答案
我很正确地理解您的问题是:我有一些包含多个元素的JSON数据.如何遍历javascript中的那些元素?如果正确,则需要三个步骤.
Am I right in understanding that your question is: I have some JSON data with multiple elements. How do I traverse those elements in javascript? If that is correct, you need three steps.
首先将JSON转换为对象
First convert the JSON to an object
var dataobj = JSON_parse(data)
然后您可以在对象中获取键的数组
then you can get an array of the keys in the object
var datakeys = Object.keys(dataobj)
然后使用for循环遍历obj
then you traverse the obj using a for loop
for (var i = 0; i < datakeys.length; i++) {
var dataval = dataobj[datakeys[i]]
// make your new row with the data
}
这篇关于使用数据(Json),为数组中的每个对象创建新的元素,行和列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!