js根據json物件陣列動態生成表格
阿新 • • 發佈:2019-02-17
- 需求:(1).ajax取得json物件陣列後,根據陣列內所有json物件的所有key和value生成相應的表格標題和表格資料;
(2).不顯示json資料的某些key;
(3).對某些key進行先後排序顯示。
2.js程式碼:
(function(){
$("#queryButton").bind('click',function() {
$.ajax({
url:"...",
type:"POST",
dataType:"json",
contentType:"application/json",
data:{},
success: function(response, statusText, xhr) {},
error: function(jqXHR, textStatus, errorThrown) {
alert("ajax error");
//var responseJson = response.hits.hits;
var tableHeaderColumnsTemp = [];
var tableHeaderColumns = [];
var firstRowTableHeaderToFrontSort = new Array("firstRowHeader004","firstRowHeader005","firstRowHeader002","firstRowHeader001");
var excludeTableHeaderColumns = new Array("vjkigjeiogj","firstRowHeader003");
var _sourceJsonObjArray = [
{
"firstRowHeader001": 495934,
"firstRowHeader002": "log",
"firstRowHeader003": "cat",
"firstRowHeader004": [
"beats_input_codec_plain_applied",
"beats_input_codec_plain_applied2",
"beats_input_codec_plain_applied3" ,
"beats_input_codec_plain_applied4"
],
"firstRowHeader005": {
"secondRowHeader001": {
"thirdRowHeader001": "dfjfiue"
},
"secondRowHeader002": {
"thirdRowHeader002": "Marktet"
},
"key1": {
"key2": {
"key3":{
"key4":{
"key5":["mostInnerValue1","mostInnerValue2","mostInnerValue3"],
"key6":["mostInnerValue4","mostInnerValue5","mostInnerValue6"]
}
}
}
}
}
},
{
"nvurhvyuefoe": ["value001","value002","value003","value004"],
"rthhn": "jtjnbgbhruik",
"abc": {
"abd": "grthtyjkyiu",
"bcd": "gfethntyjymy",
"acd": "wqdegvgtrhx"
},
"dedwefwef": "hythvtrbnyoq",
"grtgr": {
"7u65uj": {
"mghhmujty": "rtetj"
},
"ujjtyjt": {
"basic": "Marktet"
},
"jhjtkjtyr": "loiulyhgd",
"dadqwe": 1,
"fdsfw": 42332,
"hhrtghtr": true,
"cfjewiofhr": "jfu",
"enfydqeg": 245577803567,
"mbufhgr": "gtoeigjigo",
"dewgbtyj": "fertrhyuknbfg"
}
},
{
"vjkigjeiogj": [
"rwvebverqweju",
"jtyjrgcvfgvrthyoi"
],
"firstRowHeader005": {
"secondRowHeader001": {
"thirdRowHeader003": "dfjfiue"
},
"secondRowHeader002": {
"thirdRowHeader004": "Marktet"
},
"secondRowHeader003": {
"thirdRowHeader005": "Marktet"
},
},
"last":{"key1": {
"key2": {
"key3":{
"key4":{
"key5":{
"key6":[{"key7":"value7"},{"key7-":"value7-"}]
}
}
}
}}}}];
//根據json物件陣列得到所有標題
for (var i = 0; i < _sourceJsonObjArray.length; i++) {
var _sourceJsonObj = _sourceJsonObjArray[i];
for(var p in _sourceJsonObj){
getTableHeaderFieldsArray(p,_sourceJsonObj[p],tableHeaderColumnsTemp,excludeTableHeaderColumns);
}
}
//去掉重複的標題
$.unique(tableHeaderColumnsTemp);
//所有含有相同上層父標題的標題存放在陣列的相鄰位置
var tableHeaderRowNum = getTableHeaderRowNum(tableHeaderColumnsTemp);
var tableHeaderColumnsTemp2 = [];
placeHeaderColumns(0,tableHeaderColumnsTemp,tableHeaderRowNum,tableHeaderColumnsTemp2);
//第一行標題排序
sortFirstRowHeaderColumns(firstRowTableHeaderToFrontSort,tableHeaderColumnsTemp2,tableHeaderColumns);
//建立或重新整理表格
createTable(tableHeaderColumns,_sourceJsonObjArray,excludeTableHeaderColumns);
}})
});
})();
function placeHeaderColumns(i,tableHeaderColumnsTemp,tableHeaderRowNum,tableHeaderColumnsTemp2) {
var tableHeaderColumnsTemp3 = [];
var fatherFieldsArray = [];
for (var index in tableHeaderColumnsTemp) {
var header = tableHeaderColumnsTemp[index];
if (header.indexOf(".") <= 0) {
tableHeaderColumnsTemp3.push(header);
} else if (header.indexOf(".") > 0) {
if ((header.split(".").length - 1) <= i) {
tableHeaderColumnsTemp3.push(header);
continue;
} else {
var fields = header.split(".");
var fatherFields = "";
for (var j = 0; j <= i; j++) {
if (j == 0) {
fatherFields = fields[0];
} else {
fatherFields += "." + fields[j];
}
}
if (!hasDirectHeader(fatherFields,fatherFieldsArray)) {
for(var innerIndex in tableHeaderColumnsTemp) {
var innerHeader = tableHeaderColumnsTemp[innerIndex];
if (innerHeader.indexOf(".") > 0 && (innerHeader.split(".").length - 1) > i) {
var innerHeaderArray = innerHeader.split(".");
var innerFatherFields
for (var j = 0; j <= i; j++) {
if (j == 0) {
innerFatherFields = innerHeaderArray[0];
} else {
innerFatherFields += "." + innerHeaderArray[j];
}
}
if (innerFatherFields == fatherFields) {
tableHeaderColumnsTemp3.push(innerHeader);
}
}
}
fatherFieldsArray.push(fatherFields);
} else {
continue;
}
}
}
}
if (i < (tableHeaderRowNum - 2)) {
placeHeaderColumns(i+1,tableHeaderColumnsTemp3,tableHeaderRowNum,tableHeaderColumnsTemp2);
} else {
for (var index in tableHeaderColumnsTemp3) {
tableHeaderColumnsTemp2.push(tableHeaderColumnsTemp3[index]);
}
}
}
function sortFirstRowHeaderColumns(firstRowTableHeaderToFrontSort,tableHeaderColumnsTemp,tableHeaderColumns) {
for (var index in firstRowTableHeaderToFrontSort) {
var sortHeader = firstRowTableHeaderToFrontSort[index];
if (hasDirectHeader(sortHeader,tableHeaderColumnsTemp)) {
tableHeaderColumns.push(sortHeader);
} else if (hasSubHeaderContainingHeader(sortHeader,tableHeaderColumnsTemp)) {
for (var j = 0,len = tableHeaderColumnsTemp.length; j <len; j++) {
if (tableHeaderColumnsTemp[j].indexOf(sortHeader + ".") == 0) {
tableHeaderColumns.push(tableHeaderColumnsTemp[j]);
}
}
}
}
for (var index in tableHeaderColumnsTemp) {
var header = tableHeaderColumnsTemp[index];
var hasThisHeader = false;
for (var inIndex in tableHeaderColumns) {
if (tableHeaderColumns[inIndex] == header) {
hasThisHeader = true;
break;
}
}
if (!hasThisHeader) {
tableHeaderColumns.push(header);
}
}
}
function hasDirectHeader(field,tableHeaderColumns) {
var has = false;
for (var index in tableHeaderColumns) {
if (tableHeaderColumns[index] == field) {
has = true;
break;
}
}
return has;
}
function hasSubHeaderContainingHeader(field,tableHeaderColumns) {
var has = false;
for (var index in tableHeaderColumns) {
if (tableHeaderColumns[index].indexOf(field + ".") == 0) {
has = true;
break;
}
}
return has;
}
function getTableHeaderFieldsArray(key,value,tableHeaderColumns,excludeTableHeaderColumns) {
if (value instanceof Array) {
for(var i=0,len=value.length;i<len;i++) {
var iterationValue = value[i];
if (iterationValue instanceof Object) {
for (var p in iterationValue) {
getTableHeaderFieldsArray(key + "." + p,iterationValue[p],tableHeaderColumns,excludeTableHeaderColumns);
}
} else {
if (!isExcludeTableHeaderColumn(excludeTableHeaderColumns,key)) {
tableHeaderColumns.push(key);
}
}
}
} else if (value instanceof Object) {
for(var p in value){
getTableHeaderFieldsArray(key + "." + p,value[p],tableHeaderColumns,excludeTableHeaderColumns);
}
} else {
if (!isExcludeTableHeaderColumn(excludeTableHeaderColumns,key)) {
tableHeaderColumns.push(key);
}
}
}
function isExcludeTableHeaderColumn(excludeTableHeaderColumns,field) {
var isExcludeTableHeaderColumn1 = false;
for (var k = 0; k < excludeTableHeaderColumns.length; k++) {
if (excludeTableHeaderColumns[k] == field) {
isExcludeTableHeaderColumn1 = true;
break;
}
}
return isExcludeTableHeaderColumn1;
}
function getTableHeaderRowNum(tableHeaderColumns) {
var tableHeaderRowNum = 1;
for (var i = 0; i < tableHeaderColumns.length; i++) {
if (tableHeaderColumns[i].indexOf(".") > 0) {
var fields = tableHeaderColumns[i].split(".");
if (fields.length > tableHeaderRowNum) {
tableHeaderRowNum = fields.length;
}
}
}
return tableHeaderRowNum;
}
function createTable(tableHeaderColumns,_sourceJsonObjArray,excludeTableHeaderColumns) {
if ($("#logTable").length > 0) {
$("#logTable").remove();
}
if (_sourceJsonObjArray.length == 0) {
alert("無結果");
return;
}
//表格標題行行數
var tableHeaderRowNum = getTableHeaderRowNum(tableHeaderColumns);
//建立表格
var table = $("<table id = \"logTable\" aligh=\"center\" border=\"1\" cellspacing=\"0\" cellpadding=\"0\">");
table.appendTo($("#logTableDiv"));
//建立表格標題
recursionToCreateTableHeader(table,0,tableHeaderRowNum,tableHeaderColumns);
//填充資料
fillDataToTable(table,tableHeaderColumns,_sourceJsonObjArray,excludeTableHeaderColumns);
$("#logTable").append("</table>");
}
function recursionToCreateTableHeader(table,i,tableHeaderRowNum,tableHeaderColumns) {
var trHeader = $("<tr></tr>");
trHeader.appendTo(table);
var tableHeaderColumnsForSecondRow = [];
var multiColumnHeaderArray = [];
for (var j = 0; j < tableHeaderColumns.length; j++) {
if (tableHeaderColumns[j].indexOf(".") < 0) {
if (i == 0) {
var td = $("<td aligh=\"center\" rowspan='" + (tableHeaderRowNum - i) + "'>" + tableHeaderColumns[j] + "</td>");
td.appendTo(trHeader);
}
} else if (tableHeaderColumns[j].split(".").length > i) {
var headersArray = tableHeaderColumns[j].split(".");
var header = headersArray[i];
if (tableHeaderColumns[j].split(".").length - i == 1) {
var td = $("<td aligh=\"center\" rowspan='" + (tableHeaderRowNum - i) + "'>" + header + "</td>");
td.appendTo(trHeader);
continue;
}
var headerToCompare = "";
for (var k = 0; k <= i; k++) {
if (k == 0) {
headerToCompare = headersArray[0];
} else {
headerToCompare = headerToCompare + "." + headersArray[k];
}
}
var subHeadersNum = 0;
for (var k = 0; k < tableHeaderColumns.length; k++) {
if (tableHeaderColumns[k].indexOf(headerToCompare + ".") == 0) {
subHeadersNum++;
}
}
//tableHeaderColumnsForSecondRow.push(tableHeaderColumns[j].replace(header + ".",""));
var has = false;
if (multiColumnHeaderArray.length > 0) {
var len = multiColumnHeaderArray.length;
while (--len >= 0) {
if (multiColumnHeaderArray[len] == headerToCompare) {
has = true;
break;
}
}
}
if (subHeadersNum > 1) {
if (has) {
continue;
} else {
var td = $("<td aligh=\"center\" colspan='" + subHeadersNum + "'>" + header + "</td>");
td.appendTo(trHeader);
multiColumnHeaderArray.push(headerToCompare);
}
} else {
var td = $("<td aligh=\"center\">" + header + "</td>");
td.appendTo(trHeader);
}
}
}
if (i <= tableHeaderRowNum) {
recursionToCreateTableHeader(table,i+1,tableHeaderRowNum,tableHeaderColumns);
}
}
function fillDataToTable(table,tableHeaderColumns,_sourceJsonObjArray,excludeTableHeaderColumns) {
for (var i = 0; i < _sourceJsonObjArray.length; i++) {
var thisObjHeaderFieldArray = [];
var thisObjHeaderFieldAndValueArray = [];
var _sourceJsonObj = _sourceJsonObjArray[i];
for(var p in _sourceJsonObj){//遍歷json物件的每個key/value對,p為key
getTableHeaderFieldsArray(p,_sourceJsonObj[p],thisObjHeaderFieldArray,excludeTableHeaderColumns);
}
for(var p in _sourceJsonObj){
getTableHeaderFieldsAndValueArray(p,_sourceJsonObj[p],thisObjHeaderFieldAndValueArray,excludeTableHeaderColumns);
}
$.unique(thisObjHeaderFieldArray);
//得到物件所佔的表格最大行數
var thisObjHeaderRepetableFields = [];
for (var j=0,len=thisObjHeaderFieldAndValueArray.length;j<len;j++) {
var obj = thisObjHeaderFieldAndValueArray[j];
for (var key in obj) {
thisObjHeaderRepetableFields.push(key);
}
}
var fieldDataNumsObj={};
for(var j=0,len=thisObjHeaderRepetableFields.length;j<len;j++){
if(fieldDataNumsObj[thisObjHeaderRepetableFields[j]]){
fieldDataNumsObj[thisObjHeaderRepetableFields[j]]++;
} else{
fieldDataNumsObj[thisObjHeaderRepetableFields[j]]=1;
}
}
var thisObjTableRowNum = 0;
for (var key in fieldDataNumsObj) {
var num = fieldDataNumsObj[key];
if (num > thisObjTableRowNum) {
thisObjTableRowNum = num;
}
}
recursionToFillSingleObjDataToTable(0,table,tableHeaderColumns,thisObjHeaderFieldArray,thisObjHeaderFieldAndValueArray,thisObjTableRowNum,fieldDataNumsObj);
}
}
function getTableHeaderFieldsAndValueArray(key,value,thisObjHeaderFieldAndValueArray,excludeTableHeaderColumns) {
if (value instanceof Array) {
for(var i = 0, l = value.length; i < l; i++) {
var iterationValue = value[i];
if (iterationValue instanceof Object) {
for (var p in iterationValue) {
getTableHeaderFieldsAndValueArray(key + "." + p,iterationValue[p],thisObjHeaderFieldAndValueArray,excludeTableHeaderColumns);
}
} else {
if (!isExcludeTableHeaderColumn(excludeTableHeaderColumns,key)) {
var obj = {};
obj[key] = iterationValue;
thisObjHeaderFieldAndValueArray.push(obj);
}
}
}
} else if (value instanceof Object) {
for(var p in value){//遍歷json物件的每個key/value對,p為key
getTableHeaderFieldsAndValueArray(key + "." + p,value[p],thisObjHeaderFieldAndValueArray,excludeTableHeaderColumns);
}
} else {
if (!isExcludeTableHeaderColumn(excludeTableHeaderColumns,key)) {
var obj = {};
obj[key] = value;
thisObjHeaderFieldAndValueArray.push(obj);
}
}
}
function recursionToFillSingleObjDataToTable(count,table,tableHeaderColumns,thisObjHeaderFieldArray,thisObjHeaderFieldAndValueArray,thisObjTableRowNum,fieldDataNumsObj) {
var trHeader = $("<tr></tr>");
trHeader.appendTo(table);
var subTableHeaderColumns = [];
var subThisObjHeaderFieldAndValueArray = [];
//填充資料
for (var i = 0; i < tableHeaderColumns.length; i++) {
var header = tableHeaderColumns[i];
var containThisHeader = false;
for (var j = 0; j < thisObjHeaderFieldArray.length; j++) {
var thisObjHeader = thisObjHeaderFieldArray[j];
if (thisObjHeader == header) {
containThisHeader = true;
var thisObjHeaderAndValueObj;
for (var k = 0; k < thisObjHeaderFieldAndValueArray.length; k++) {
thisObjHeaderAndValueObj = thisObjHeaderFieldAndValueArray[k];
if (thisObjHeaderAndValueObj[thisObjHeader] != undefined) {
var thisObjHeaderValue = thisObjHeaderAndValueObj[thisObjHeader];
var fieldDataNum = fieldDataNumsObj[thisObjHeader];
thisObjHeaderFieldAndValueArray[k] = "";
var rowSpan;
if (fieldDataNum > 1) {
rowSpan = 1;
subTableHeaderColumns.push(thisObjHeader);
} else if (fieldDataNum == 1) {
rowSpan = thisObjTableRowNum - count;
}
var td = $("<td aligh=\"center\" rowspan='" + rowSpan + "'>" + thisObjHeaderValue + "</td>");
td.appendTo(trHeader);
fieldDataNumsObj[thisObjHeader] = fieldDataNum - 1;
break;
}
}
break;
}
}
if (containThisHeader == false) {
var td = $("<td aligh=\"center\" rowspan='" + thisObjTableRowNum + "'></td>");
td.appendTo(trHeader);
}
}
if (count < thisObjTableRowNum) {
recursionToFillSingleObjDataToTable(count + 1,table,subTableHeaderColumns,thisObjHeaderFieldArray,thisObjHeaderFieldAndValueArray,thisObjTableRowNum,fieldDataNumsObj)
}
}
4.程式碼說明:(1)如果要親測的話,除了該js檔案,還需要一個引用該js檔案html檔案,需要在html檔案裡引入jQuery相關檔案;(2).把處理資料的程式碼寫在error回撥函式裡,是為了方便測試,只要有瀏覽器就可以測試,ajax的請求url可以隨便寫,報錯了就直接進入到error回撥函式裡,在error回撥函式裡寫死資料,在這裡可以向陣列中新增任意深度的json物件,不必每個json物件的key都是一樣。
5.生成表格結果如下: