如何在DataTables中映射索引数组数据源

时间:2018-01-30 17:00:29

标签: javascript json datatables

假设我有一个数组作为DataTables的数据源,通过AJAX提供

{
  "data": [
    [
      "https://stackoverflow.com/questions/ask",
      "Tiger Nixon",
      "System Architect",
      "Edinburgh",
      "5421",
      "2011/04/25",
      "$320,800"
    ]
  ]
}

我想忽略第一个单元格而不将其作为列输出,那么如何将索引数据映射到列?我已经尝试过这个,但它给出了一个错误:

$(document).ready(function() {
    $('#example').DataTable( {
        "ajax": "data/objects.txt",
        "columns": [
            { "data": [1] },
            { "data": [2] },
            { "data": [3] },
            { "data": [4] },
            { "data": [5] },
            { "data": [6] }
        ]
    } );
} );

Uncaught TypeError: Cannot read property 'mData' of undefined

我也尝试引用像这样的索引

"data": 1

也不起作用。

如果源是带键的对象,则引用将如下所示:

        "columns": [
            { "data": "name" },
            { "data": "position" },
            { "data": "office" },
            { "data": "extn" },
            { "data": "start_date" },
            { "data": "salary" }
        ]

2 个答案:

答案 0 :(得分:0)

var obj = {}
var keys = ['name', 'job', 'location', 'number', 'date', 'salary']
var arr = [
  'https://stackoverflow.com/questions/ask',
  'Tiger Nixon',
  'System Architect',
  'Edinburgh',
  '5421',
  '2011/04/25',
  '$120000'
]
.filter((item, i) => !!i)
.forEach((v, i) => obj[keys[i]] = v)

console.log(obj)

答案 1 :(得分:0)

我自己找到了解决方案,这段代码会使第一个单元格不可见并显示其他单元格:

$(document).ready(function() {
    $('#example').DataTable( {
        "ajax": "data/objects.txt",
        "columnDefs": [
            { "targets": [0], "visible": false },
            { "targets": '_all', "visible": true }
        ]
    } );
} );