我有一个表,我用 jquery(html) 填充它。为了限制显示行,我一直在尝试将此表更改为数据表。
我有这样的数据:
dataArray = [{
id: 1,
props: {
abc: 123,
def: 456,
ghi: 789
},
features: {
zxc: 01,
cvb: 02,
nmn: 03
}
},
{
id: 2,
props: {
abc: 002,
def: 258,
ghi: 965
},
features: {
zxc: 52,
cvb: 21,
nmn: 75
}
},
{
id: 3,
props: {
abc: 352,
def: 365,
ghi: 778
},
features: {
zxc: 21,
cvb: 45,
nmn: 03
}
},
]
比方说,我想显示 id、abc(来自 props)、zxc(来自功能)。
我尝试通过转换 JSON 在数据表中使用,但没有成功。我不确定如何在数据表上显示这些数据。
此 dataArray 在应用程序内部更新,它不是外部数据。
你能帮我一下吗?
最佳答案
据我所知,您需要将 JSON 属性及其相应的值更改为字符串。如果您需要对整数进行任何算术运算,您可以随时使用parseInt()
。然后在 DataTable()
调用中指定 data
和 columns
属性,如下所示:
var dataArray = [{
"id": "1",
"props": {
"abc": "123",
"def": "456",
"ghi": "789"
},
"features": {
"zxc": "01",
"cvb": "02",
"nmn": "03"
}
},
{
"id": "2",
"props": {
"abc": "002",
"def": "258",
"ghi": "965"
},
"features": {
"zxc": "52",
"cvb": "21",
"nmn": "75"
}
},
{
"id": "3",
"props": {
"abc": "352",
"def": "365",
"ghi": "778"
},
"features": {
"zxc": "21",
"cvb": "45",
"nmn": "03"
}
},
]
$(document).ready(function() {
$('#example').DataTable( {
data: dataArray,
"columns": [
{ data: "id" },
{ data: "props.abc" },
{ data: "features.zxc" },
]
} );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.19/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet"/>
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>ID</th>
<th>Props</th>
<th>Features</th>
</tr>
</thead>
<tfoot>
<tr>
<th>ID</th>
<th>Props</th>
<th>Features</th>
</tr>
</tfoot>
</table>
关于javascript - DataTables 从 JSON 或 JS Array&Objects 填充表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51671859/