我有以下結構:創建複雜的表結構
[{
"ID": "1",
"Country": "Italy",
"Animals": {
"dog": {
"1": {
"name": "Bailey",
"age": "5"
},
"2": {
"name": "Charlie",
"age": "3"
}
},
"cat": {
"1": {
"name": "Luna",
"age": "7"
},
"2": {
"name": "Biscuit",
"age": "1"
}
}
}
}, {
"ID": "4",
"Country": "France",
"Animals": {
"cat": {
"1": {
"name": "Chloe",
"age": "8"
},
"2": {
"name": "Jasper",
"age": "2"
}
},
"mouse": {
"1": {
"name": "Skittles",
"age": "7"
},
"2": {
"name": "Indy",
"age": "9"
},
"3": {
"name": "Goldie",
"age": "3"
}
}
}
}, {
"ID": "6",
"Country": "Spain",
"Animals": {
"cat": {
"1": {
"name": "Toby",
"age": "7"
},
"2": {
"name": "Simba",
"age": "2"
}
}
}
}, {
"ID": "9",
"Country": "Germany",
"Animals": {
"mouse": {
"1": {
"name": "Crimsin",
"age": "1"
}
}
}
}]
我想要顯示它,如下表:
這是我的方法:
$.each(arr, function(key, value) {
var rowspan = Object.keys(arr[key].Animals).length;
var tr = "";
c = 0;
$.each(value, function(key2, value2) {
if (key2 != "animals") {
if (rowspan < 1) {
rowspan = 1;
}
tr += '<td rowspan=' + rowspan + '>' + value2 + '</td>';
} else {
$.each(value2, function(key3, value3) {
var tr2_temp = "";
tr2_temp += "<td>" + key3 + "</td>";
$.each(value3, function(key4, value4) {
tr2_temp += "<td>" + value4 + "</td>";
});
if (c == 0) {
$('#myTab tr:eq(' + parseInt(key + 1) + ')').append(tr2_temp)
c++;
} else {
$('#myTab tr:eq(' + parseInt(key + 1) + ')').after(tr2_temp)
c = 0;
}
});
}
});
console.log(tr)
$('#myTab > tbody:last-child').append('<tr>' + tr + '</tr>');
});
但它沒有幫助。
有沒有辦法動態地做到這一點,以便我沒有如此指定每一列?
請注意,這是一個簡化的例子。在真實情況下,還有更多的屬性。
看到你改變的數據結構,但仍應考慮做'Animals'的數組。使用 – charlietfl