我想用 colspan 创建一个 html 表头,但我迷路了; 我有这个 json:
var metadata = [{
"colIndex": 0,
"colType": "String",
"colName": "PM"
}, {
"colIndex": 1,
"colType": "String",
"colName": "PROD"
}, {
"colIndex": 2,
"colType": "Numeric",
"colName": "NR/M1"
}, {
"colIndex": 3,
"colType": "Numeric",
"colName": "NR/M2"
}, {
"colIndex": 4,
"colType": "Numeric",
"colName": "NR/M3"
}, {
"colIndex": 5,
"colType": "Numeric",
"colName": "NR/M4"
}, {
"colIndex": 6,
"colType": "Numeric",
"colName": "NR/M5"
}, {
"colIndex": 7,
"colType": "Numeric",
"colName": "NR ART/M6"
}, {
"colIndex": 8,
"colType": "Numeric",
"colName": "NR ART/M1"
}, {
"colIndex": 9,
"colType": "Numeric",
"colName": "NR ART/M2"
}, {
"colIndex": 10,
"colType": "Numeric",
"colName": "NR ART/M3"
}, {
"colIndex": 11,
"colType": "Numeric",
"colName": "NR ART/MX"
}];
表格标题主要基于拆分“colType”:“Numeric”
+------+-------+-----+--------+-----+-----+-----+-----+------+----+----+----+
| | | NR | NR ART |
+ PAM | PROD +-----+--------+-----+-----+-----+-----+------+----+----+----+
| | M1 | M2 | M3 | M4 | M5 | M6 | M1 | M2 | M3 | MX |
+------+-------+-----+--------+-----+-----+-----+-----+------+----+----+----+
首先我尝试拆分 colName,其中 colType 是数字
var arr = [], a;
$.each(metadata, function (i, v) {
arr.push(v.colName.split("/"));
a = v.colName.split("/").length;
});
接下来,我得到了独特的 parent (?),但我能用它做什么呢? 我想我必须在层次结构中遍历这个数组(父级 - 子级,然后构建 html header )。
数组是动态的。
有什么建议吗?请并谢谢您。
最佳答案
下面的代码应该可以完成工作,请检查
var arr = {}, a;
$.each(metadata, function (i, v) {
arr[v.colName.split("/")[0]] = arr[v.colName.split("/")[0]].push(v.colName.split("/")[1]) || [] ;
});
为了显示它
for(t1 in arr){
if(t1.length > 0){
//has children element
}
else{
//has only 1 element
}
}
关于Javascript 从 json 创建复杂的表头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27447058/