gpt4 book ai didi

javascript - 使用另一个数组作为引用获取对象属性值

转载 作者:行者123 更新时间:2023-12-03 11:10:28 25 4
gpt4 key购买 nike

我有两个数组,一个是像这样的对象数组:

[
Object {ID: "2006", Description: "ABCDEFG"}
Object {ID: "2102", Description: "HIJKLMN"}
Object {ID: "2616", Description: "OPQRSTU"}
]

另一个是具有属性的数组

["ID", "Description"]

我正在尝试使用 JQuery .each 函数来捕获使用数组作为引用的值并创建一个 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>'

但是使用这种方式,我总是得到值未定义

你能帮我创建一个函数来接收一个对象数组并检索一个表吗?或者帮我找出我做错了什么也没关系。

最佳答案

每个循环中存在一些错误,请尝试此代码片段,并密切注意 //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);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
</body>

关于javascript - 使用另一个数组作为引用获取对象属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27621385/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com