我有一个这种格式的json数组:
[
{
id : "001",
name : "apple",
category : "fruit",
color : "red"
},
{
id : "002",
name : "melon",
category : "fruit",
color : "green"
},
{
id : "003",
name : "banana",
category : "fruit",
color : "yellow"
}
]
现在,我想在Javascript或jQuery中以表格格式解析和显示它。该表有四列,每列指示此数组中每个元素的每个属性。该表的第一行是这四个键的名称。其他行是这些键的值。
我不知道如何编写JavaScript代码来实现此功能。你能帮我解决这个问题吗?
答案 0 :(得分:20)
var obj=[
{
id : "001",
name : "apple",
category : "fruit",
color : "red"
},
{
id : "002",
name : "melon",
category : "fruit",
color : "green"
},
{
id : "003",
name : "banana",
category : "fruit",
color : "yellow"
}
]
var tbl=$("<table/>").attr("id","mytable");
$("#div1").append(tbl);
for(var i=0;i<obj.length;i++)
{
var tr="<tr>";
var td1="<td>"+obj[i]["id"]+"</td>";
var td2="<td>"+obj[i]["name"]+"</td>";
var td3="<td>"+obj[i]["color"]+"</td></tr>";
$("#mytable").append(tr+td1+td2+td3);
}
答案 1 :(得分:10)
使用jquery $.each
您可以访问所有数据,也可以像这样设置表格
<table style="width: 100%">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Category</th>
<th>Color</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
$.each(data, function (index, item) {
var eachrow = "<tr>"
+ "<td>" + item[1] + "</td>"
+ "<td>" + item[2] + "</td>"
+ "<td>" + item[3] + "</td>"
+ "<td>" + item[4] + "</td>"
+ "</tr>";
$('#tbody').append(eachrow);
});
答案 2 :(得分:3)
var jArr = [
{
id : "001",
name : "apple",
category : "fruit",
color : "red"
},
{
id : "002",
name : "melon",
category : "fruit",
color : "green"
},
{
id : "003",
name : "banana",
category : "fruit",
color : "yellow"
}
]
var tableData = '<table><tr><td>Id</td><td>Name</td><td>Category</td><td>Color</td></tr>';
$.each(jArr, function(index, data) {
tableData += '<tr><td>'+data.id+'</td><td>'+data.name+'</td><td>'+data.category+'</td><td>'+data.color+'</td></tr>';
});
$('div').html(tableData);
答案 3 :(得分:2)
var data = [
{
id : "001",
name : "apple",
category : "fruit",
color : "red"
},
{
id : "002",
name : "melon",
category : "fruit",
color : "green"
},
{
id : "003",
name : "banana",
category : "fruit",
color : "yellow"
}
];
for(var i = 0, len = data.length; i < length; i++) {
var temp = '<tr><td>' + data[i].id + '</td>';
temp+= '<td>' + data[i].name+ '</td>';
temp+= '<td>' + data[i].category + '</td>';
temp+= '<td>' + data[i].color + '</td></tr>';
$('table tbody').append(temp));
}