从列数据行中获取json数据

时间:2017-03-19 17:19:28

标签: javascript jquery json datatables

我有像bellow一样的数据表

<table id="example" class="display" width="100%" cellspacing="0">
        <thead>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Age</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </thead>

        <tbody>
            <tr>
                <td>Tiger Nixon</td>
                <td>System Architect</td>
                <td>Edinburgh</td>
                <td>61</td>
                <td>2011/04/25</td>
                <td>$320,800</td>
            </tr>

        </tbody>
    </table>

点击按钮,我写下以下代码

console.log(JSON.stringify($('#example').dataTable().fnGetData()))

上面的代码返回下面的JSON

[["Tiger Nixon","System Architect","Edinburgh","61","2011/04/25","$320,800"],["Garrett Winters","Accountant","Tokyo","63","2011/07/25","$170,750"],["Ashton Cox","Junior Technical Author","San Francisco","66","2009/01/12","$86,000"]]

但我希望这个Row -Column像

一样明智
["Name":"Tiger Nixon","Position":"System Architect","Office":"Edinburgh","Age":"61","Start date":"2011/04/25","Salary":"$320,800"]

如何获取格式以上的数据?

2 个答案:

答案 0 :(得分:0)

您可以使用重新映射功能来创建包含具有属性和值的对象的数组:

var rawData = [
    ["Tiger Nixon","System Architect","Edinburgh","61","2011/04/25","$320,800"],
    ["Garrett Winters","Accountant","Tokyo","63","2011/07/25","$170,750"],
    ["Ashton Cox","Junior Technical Author","San Francisco","66","2009/01/12","$86,000"]
];
var template = ['Name', 'Position', 'Office', 'Age', 'Start date', 'Sallary'];

function mapData(data, template) {
    remapped = []
    for (subArray in data) {
        remappedSubArray = []
        for (element in data[subArray]) {
            remappedSubArray[template[element]] = data[subArray][element]
        }
        remapped.push(remappedSubArray);
    }

    return remapped;
}


remapped = mapData(rawData, template);

console.log(remapped[1]['Name']); // will output Garrett Winters

答案 1 :(得分:0)

fnGetData已弃用,但仍可使用。

您可以使用$('#example').dataTable().api().columns().header()获取标题。

所以你可以建立一个这样的函数:

function getRCData() {
 oTable = $('#example').dataTable();
 var api = oTable.api();
 var header = api.columns().header();
 var data = oTable.fnGetData();
 var results = [];   

 for (var i=0;i<data.length;i++) {
    results.push({});
    for (var j=0;j<data[0].length;j++) {
        results[i][header[j].innerText] = data[i][j];
    }
 }   

 return JSON.stringify(results);   
}