我正在尝试按如下方式在 javascript 中呈现表格:
$('#serviceTable').DataTable({
responsive: true,
aaData: services,
bJQueryUI: true,
aoColumns: [
{ mData: 'service_name' },
{ mData: 'last_incident' },
{ mData: 'integration' }
]
});
现在 integration
字段基本上是一个 json 对象数组,如下所示
[{"name":"abc","key":"123"},{"name":"xyz","key":"1234"}]
这是表定义:
<table id="serviceTable" class="table table-bordered table-striped">
<thead>
<tr>
<th data-field="service_name" data-formatter="LinkFormatter">Service</th>
<th data-field="last_incident">Last Incident</th>
<th data-field="integration">Integration</th>
</tr>
</thead>
</table>
所以在 UI 上,我可以在列集成中看到 [object Object],[object Object]
。我们如何遍历 json 数组以在列中显示 name
字段
最佳答案
按如下方式使用render
。
{ mData: 'integration',
"render": function(value, type, row, meta){
var output="";
for(var i=0;i<value.length;i++){
output += value[i].name ;
if(i< value.length-1){
output +=", ";
}
}
return output;
}
工作示例:
<head>
<link rel="stylesheet" href="//cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css">
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="//cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
</head>
<body>
<table id="serviceTable" class="table table-bordered table-striped">
<thead>
<tr>
<th data-field="service_name" data-formatter="LinkFormatter">Service</th>
<th data-field="last_incident">Last Incident</th>
<th data-field="integration">Integration</th>
</tr>
</thead>
</table>
</body>
<script>
var service=[{"service_id" :"1", "service_name":"s1","last_incident":"i1","integration":[{"name":"abc","key":"123"},{"name":"xyz","key":"1234"}]}
,{"service_id" :"2", "service_name":"s2","last_incident":"i1","integration":[{"name":"abc","key":"123"},{"name":"xyz","key":"1234"}]}
];
$('#serviceTable').DataTable({
responsive: true,
aaData: service,
bJQueryUI: true,
aoColumns: [
{
mData: 'service_name' ,
"render": function(value, type, row, meta){
return "<a href='/service/"+row.service_id+"'>"+value+"</a>";
}
},
{ mData: 'last_incident' },
{ mData: 'integration',
"render": function(value, type, row, meta){
var output="";
for(var i=0;i<value.length;i++){
output += value[i].name ;
if(i< value.length-1){
output +=", ";
}
}
return output;
}
}
]
});
</script>
关于javascript - 如何遍历数据表中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49146266/