我有一些JSON数据想要从中创建一个表,但是我从控制台TypeError: obj.labels[i].getAttribute is not a function
中收到此错误。
创建表头是可以的,只有在尝试用数据填充表时才会出现错误。
我希望汽车桌子的标题为[id, carname, year, registration]
错误来自以下行:span.innerText = obj.labels[i].getAttribute(attrs[j]);
我不知道为什么会出错,我需要一些帮助来提取汽车数据并填充表格。
var attrs = ["id", "name", "year", "registration"];
var jsonString =
'{\n' +
' "labels": [\n' +
' {\n' +
' "name": "test",\n' +
' "age": 33,\n' +
' "contact": test,\n' +
' "cars": [\n' +
' {"id": 2222, "carname": "ford", "year": 2000, "registration": cd60}\n' +
' {"id": 3333, "carname": "BMW", "year": 2012, "registration": fs41}\n' +
' ]\n' +
' }\n' +
' ]\n' +
'}\n' +
'';
var obj = JSON.parse(jsonString);
//create table
var myTableDiv = document.getElementById("mytable")
var table = document.createElement('table');
var tableBody = document.createElement('tbody');
table.appendChild(tableBody);
//header
for (var i = 0; i < obj.labels.length; i++) {
var tr = document.createElement('tr');
for (var j = 0; j < attrs.length; j++) {
var td = document.createElement('th');
td.width = '75';
var span = document.createElement("span");
span.innerText = attrs[j];
td.appendChild(span);
tr.appendChild(td);
}
tableBody.appendChild(tr);
}
//body
for (var i = 0; i < obj.labels.length; i++) {
var tr = document.createElement('tr');
for (var j = 0; j < attrs.length; j++) {
var td = document.createElement('td');
td.width = '75';
var span = document.createElement("span");
span.innerText = obj.labels[i].getAttribute(attrs[j]);
td.appendChild(span);
tr.appendChild(td);
}
tableBody.appendChild(tr);
}
myTableDiv.appendChild(table)
答案 0 :(得分:2)
如果我正确理解了您的问题,则希望在HTML表格中显示汽车详细信息。您输入的JSON数据结构如下:
labels
有一组对象(假设每个对象都是label
)cars
car
都具有属性要访问汽车的详细信息,您的代码将如下:
var attrs = ["id", "carname", "year", "registration"];
var jsonString =
'{\n' +
' "labels": [\n' +
' {\n' +
' "name": "test",\n' +
' "age": 33,\n' +
' "contact": "test",\n' +
' "cars": [\n' +
' {"id": 2222, "carname": "ford", "year": 2000, "registration": "cd60"},\n' +
' {"id": 3333, "carname": "BMW", "year": 2012, "registration": "fs41"}\n' +
' ]\n' +
' }\n' +
' ]\n' +
'}\n' +
'';
var obj = JSON.parse(jsonString);
console.log(obj)
for (var i = 0; i < obj.labels.length; i++) {
for (var j = 0; j < obj.labels[i]['cars'].length; j++) {
for (var k = 0; k < attrs.length; k++) {
console.log(obj.labels[0]['cars'][j][attrs[k]])
}
console.log("=========")
}
}
修改
上面的迭代看起来很基础。以下是上述for循环的简短形式:
如果您想参考attrs
来阅读汽车属性:
[...obj.labels].forEach(element => {
element['cars'].forEach(car => {
for (var i = 0; i < attrs.length; i++) {
console.log(car[attrs[i]]);
}
});
});
如果您想阅读所有汽车属性:
[...obj.labels].forEach(element => {
element['cars'].forEach(car => Object.keys(car).map(attr =>
console.log(attr + " " + car[attr])));
});