我在JSON文档中有一个数组。以下是该数组中的一项:
{
"generalSolution": "Cloud",
"generalOperator": "MTN",
"genericCountry": "USA",
"vnfProductName": "vEPG;vSAPC;vSGSN-MME",
"vnfRelease": "2.4;1.3;v1.2399999",
"vnfVendor": "Ericsson;Ericsson;Ericsson"
}
我想将DataTables中的数据显示为单行,如下所示:
请注意,vnf详细信息(vnfProductName
,vnfRelease
,vnfVendor
)可以具有可变数量的条目。
答案 0 :(得分:1)
使用render
选项在渲染时转换数据:
//use JSON excerpt as a data source
var srcData = [{
"generalSolution": "Cloud",
"generalOperator": "MTN",
"genericCountry": "USA",
"vnfProductName": "vEPG;vSAPC;vSGSN-MME",
"vnfRelease": "2.4;1.3;v1.2399999",
"vnfVendor": "Ericsson;Ericsson;Ericsson"
}];
//initialize DataTables
const dataTables = $('#mytable').DataTable({
data: srcData,
dom: 't',
//map all property keys (assuming, set of properties is uniform for all array entries)
//into array, expected by 'columns' option: [{title: ..., data: ...}...]
columns: Object.keys(srcData[0]).map(propertyKey => ({title: propertyKey, data: propertyKey})),
//use additionally 'columnDefs' option to apply 'render' callback to certain columns
columnDefs: [{
targets: [3, 4, 5],
//replace semicolons in each cell contents within columns 3, 4, 5 with new line tag `<br>`
render: (data, type, row, meta) => data ? data.replace(/;/g, '<br>') : ''
}]
});
<!doctype html>
<html>
<head>
<script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="application/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
<table id="mytable"></table>
</body>
</html>
答案 1 :(得分:0)
只需将;
的{{1}}替换为String#replace
。
这是一个示例。在此,原始对象被更改。如果需要,请考虑修改ID。
<br>
$(document).ready(() => {
const obj = {
"generalSolution": "Cloud",
"generalOperator": "MTN",
"genericCountry": "USA",
"vnfProductName": "vEPG;vSAPC;vSGSN-MME",
"vnfRelease": "2.4;1.3;v1.2399999",
"vnfVendor": "Ericsson;Ericsson;Ericsson"
};
for (let key in obj) {
// Here!
obj[key] = obj[key].replace(/;/g, '<br>');
}
$('#dt').DataTable({
data: [obj],
columns: [
{data: 'generalSolution'},
{data: 'generalOperator'},
{data: 'genericCountry'},
{data: 'vnfProductName'},
{data: 'vnfRelease'},
{data: 'vnfVendor'}
]
});
});