javascript - DataTables 从 JSON 或 JS Array&Objects 填充表格

标签 javascript jquery json datatable

我有一个表,我用 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
    }
},

]

比方说,我想显示 idabc(来自 props)、zxc(来自功能)。

我尝试通过转换 JSON 在数据表中使用,但没有成功。我不确定如何在数据表上显示这些数据。

此 dataArray 在应用程序内部更新,它不是外部数据。

你能帮我一下吗?

最佳答案

据我所知,您需要将 JSON 属性及其相应的值更改为字符串。如果您需要对整数进行任何算术运算,您可以随时使用parseInt()。然后在 DataTable() 调用中指定 datacolumns 属性,如下所示:

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/

相关文章:

php - Json转php,无法获取我需要的数据

javascript - Lodash 过滤以返回对象而不是长度为 1 的数组

javascript - fn.apply 第一个参数为 null 或 undefined

javascript - 从函数返回属性映射

javascript - 验证自动完成

json - 我如何在 fetch 调用中解析简单的 json 响应

javascript - 通过JS在灯箱中填充图像?

javascript - 如何使用jquery获取第二天和下个月的日期

javascript - 在dom元素中插入span而不覆盖子节点?

java - 在Windows机器上比较两个json文件