我有两个数组,一个是像这样的对象数组:
[
Object {ID: "2006", Description: "ABCDEFG"}
Object {ID: "2102", Description: "HIJKLMN"}
Object {ID: "2616", Description: "OPQRSTU"}
]
另一个是具有属性
的数组["ID", "Description"]
我尝试使用JQuery .each 函数来使用Array作为参考来捕获值,并创建一个HTML表格,如下所示:
var columns = new Array();
var strTable = '';
var tHead = '';
var tBody = '';
//Capture the columns
$.each(arrObjects, function (a, b) {
columns=Object.getOwnPropertyNames(b)
});
//Make the Table Head;
$.each(columns, function (a, b) {
tHead += '<th>'+ b +'</th>'
});
//Create table body
$.each(arrObjects, function (aa, bb) {
tBody += '<tr>'
$.each(columns, function (a, b) {
tBody += '<td>'+ bb.b +'</td>'
});
tBody += '</tr>'
})
strTable = '<table class="table"><thead><tr>' + tHead + '</tr></thead><tbody>' + tBody + '</tbody></table>'
但是使用这种方式,我总是得到值undefined
。
你能帮我创建一个接收一个对象数组的函数并检索一个表吗?或者帮助我找出我做错了什么也没关系。
答案 0 :(得分:1)
你在每个循环中都有一些错误,尝试这个片段,并密切关注//Create table body
var columns = [];
var strTable = '';
var tHead = '';
var tBody = '';
var arrObjects = [
{ID: "2006", Description: "ABCDEFG"},
{ID: "2102", Description: "HIJKLMN"},
{ID: "2616", Description: "OPQRSTU"}
];
//Capture the columns
$.each(arrObjects, function (a, b) {
columns=Object.getOwnPropertyNames(b);
});
//Make the Table Head;
$.each(columns, function (a, b) {
tHead += '<th>'+ b +'</th>';
console.log(tHead);
});
//Create table body
$.each(arrObjects, function (idx, obj) {
tBody += '<tr>';
$.each(obj, function (obj_idx, value) {
console.log(value);
tBody += '<td>'+ value +'</td>';
});
tBody += '</tr>';
});
strTable = '<table class="table"><thead><tr>' + tHead + '</tr></thead><tbody>' + tBody + '</tbody></table>';
$('body').html(strTable);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
</body>
&#13;