我有给定JSON格式的API-
{
"1":[
{"project_id":1,"project":"Alamiz City","city":1},
{"project_id":2,"project":"Alamiz Tech City","city":1},
{"project_id":3,"project":"Alamiz Down Town","city":3},
{"project_id":10,"project":"Alamiz Nature","city":2}
],
"3":[
{"project_id":4,"project":"The Tech Sky","city":1},
{"project_id":5,"project":"Alphonso","city":1}
],
"4":[
{"project_id":6,"project":"Royal Tech","city":4},
{"project_id":7,"project":"Future City","city":4}
],
"6":[{"project_id":8,"project":"Zahi Skyline","city":1}],
"2":[{"project_id":9,"project":"Souras City","city":4}]
}
此处JSON对象的Key对应于特定的构建器ID,其值是该构建器完成的所有项目的数组。
我想填充一个由builder_id和相应的构建器项目详细信息组成的表,即Project_id,项目名称和城市ID。
我想从给定的API创建一个单独的数组,然后使用它来填充表。
var project_info= new Array();
$.getJSON('https://interview.switchme.in/js/2019/project_json.php', function(data2) {
console.log(data2);
for (var n in data2){
for (var i=1;i<data2[n].length+1;i++){
project_info[n][i]=data2[n][i];
}
}
});
但是我一直收到此错误-未捕获的TypeError:无法设置未定义的属性'1'
我要填充的表的HTML代码是-
<div>
<h2>Builders Project List Table</h2>
<table id="proj_tab">
<tr>
<th>Builder_id</th>
<th>Project</th>
<th>City_id</th>
</tr>
<tr>
<td>1</td>
<td>Alamiz City</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>Alamiz Tech City</td>
<td>1</td>
</tr>
</div>
是否有一种使用$.each()
来做到这一点的方法,在数组形成之后,我应该使用
$("#proj_tab").html("<tr><td>"+project_info[i]+"</td></tr>");
还是有更好的方法呢?