1 回答
TA贡献1818条经验 获得超8个赞
如果您有嵌套数据结构,则还必须遍历嵌套元素
function buildHtmlTable(selector) {
var columns = addAllColumnHeaders(myList, selector);
for (var i = 0; i < myList.length; i++) {
var row$ = $('<tr/>');
for (var colIndex = 0; colIndex < columns.length; colIndex++) {
var cellValue = getCellValue(myList[i], columns[colIndex]);
if (cellValue == null)
cellValue = "";
row$.append($('<td/>').html(cellValue));
}
$(selector).append(row$);
}
}
function addAllColumnHeaders(myList, selector) {
var columnSet = [];
var headerTr$ = $('<tr/>');
for (var i = 0; i < myList.length; i++) {
var rowHash = myList[i];
recursiveHeaderCheck(rowHash, selector, "", columnSet, headerTr$);
}
$(selector).append(headerTr$);
return columnSet;
}
function recursiveHeaderCheck(ListElement, selector, parentKeyname, columnSet, headerTr$) {
if (typeof ListElement === 'object') {
if (parentKeyname != '')
parentKeyname = parentKeyname + '-';
for (var key in ListElement) {
var keyname = parentKeyname + key;
recursiveHeaderCheck(ListElement[key], selector, keyname, columnSet, headerTr$);
}
} else {
if ($.inArray(parentKeyname, columnSet) == -1) {
columnSet.push(parentKeyname);
headerTr$.append($('<th/>').html(parentKeyname));
}
}
}
function getCellValue(nestedStructure, columnHeader) {
var subElement = nestedStructure;
var subHeaders = columnHeader.split("-");
for (var k = 0; k < subHeaders.length; k++) {
if (typeof subElement === 'object' && subElement != null)
subElement = subElement[subHeaders[k]];
}
return subElement;
}
- 1 回答
- 0 关注
- 114 浏览
添加回答
举报