我已将数组分组,如下所示:
{
"2023-10-01": [
{
"emp_id": 1,
"name": "Aruna",
"code": "DO",
"date": "2023-10-01"
},
{
"emp_id": 2,
"name": "Aprilia",
"code": "EVE",
"date": "2023-10-01"
}
],
"2023-10-03": [
{
"emp_id": 1,
"name": "Aruna",
"code": "NIG",
"date": "2023-10-03"
},
{
"emp_id": 2,
"name": "Aprilia",
"code": "MID",
"date": "2023-10-03"
}
],
"2023-10-04": [
{
"emp_id": 2,
"name": "Aprilia",
"code": "MID",
"date": "2023-10-04"
}
],
"2023-10-05": [
{
"emp_id": 2,
"name": "Aprilia",
"code": "MID",
"date": "2023-10-05"
}
],
"2023-10-06": [
{
"emp_id": 2,
"name": "Aprilia",
"code": "MID",
"date": "2023-10-06"
}
],
"2023-10-07": [
{
"emp_id": 1,
"name": "Aruna",
"code": "DO",
"date": "2023-10-07"
},
{
"emp_id": 2,
"name": "Aprilia",
"code": "DO",
"date": "2023-10-07"
}
]
}
我想使用 Ajax 将分组数组传递到我的表。这是我期待的桌子
身份证 | 2023-10-01 | 2023-10-02 | 2023-10-03 | 2023-10-04 | 2023-10-05 | 2023-10-06 | 2023-10-07 |
---|---|---|---|---|---|---|---|
1 | 做 | 尼格 | 做 | ||||
2 | 夏娃 | 中 | 中 | 中 | 中 | 做 |
下面是我的JS代码:
$.ajax({
type: "get",
url: "{{ route('schedules.fetch-table-schedule') }}",
dataType: "json",
success: function (response) {
$.each(response.result, function( index, value ) {
var body= $("<tr><td>" + value + "</td></tr>");
$("#schedule-table #body_schedule").append(body);
});
}
抱歉,但我不知道该怎么做。任何帮助都会对我有帮助。非常感谢。
您的数据需要稍微重新排列,那么可能的解决方案可能如下所示:
const data={"2023-10-01": [{"emp_id": 1,"name": "Aruna","code": "DO","date": "2023-10-01"},{"emp_id": 2,"name": "Aprilia","code": "EVE","date": "2023-10-01"}],"2023-10-03": [{"emp_id": 1,"name": "Aruna","code": "NIG","date": "2023-10-03"},{"emp_id": 2,"name": "Aprilia","code": "MID","date": "2023-10-03"}],"2023-10-04": [{"emp_id": 2,"name": "Aprilia","code": "MID","date": "2023-10-04"}],"2023-10-05": [{"emp_id": 2,"name": "Aprilia","code": "MID","date": "2023-10-05"}],"2023-10-06": [{"emp_id": 2,"name": "Aprilia","code": "MID","date": "2023-10-06"}],"2023-10-07": [{"emp_id": 1,"name": "Aruna","code": "DO","date": "2023-10-07"},{"emp_id": 2,"name": "Aprilia","code": "DO","date": "2023-10-07"}]},
dates={},
// reorganize data:
obj=Object.entries(data).reduce((a,[k,arr])=>{
arr.forEach(o=>(a[o.emp_id]??={})[k]=o.code);
dates[k]=1;
return a;
},{}),
headers=Object.keys(dates).sort();
document.querySelector("table").innerHTML=
"<thead><th>id</th>"+headers.map(d=>`<th>${d}</th>`).join("")+"</thead>"
+"<tbody>"
+Object.entries(obj).map(([id,o])=>
`<tr><th>${id}</th>${headers.map(d=>`<td>${o[d]??""}</td>`).join("")}</tr>`).join("\n")
+"</tbody>";
td,th {border: 1px solid grey}
<table></table>