使用纯JavaScript将JSON文件转换为可排序表

时间:2015-08-14 19:56:36

标签: javascript json

我有一个名为cats.json的JSON文件。

[{
        "breed" : "Abyssinian",
        "country" : "Ethiopia",
        "coffeePreference" : "espresso",
        "picture" : "https://upload.wikimedia.org/wikipedia/commons/thumb/9/9b/Gustav_chocolate.jpg/100px-Gustav_chocolate.jpg"
    }, {
        "breed" : "Aegean",
        "country" : "Greece",
        "coffeePreference" : "medium roast, cream and sugar",
        "picture" : "https://upload.wikimedia.org/wikipedia/commons/thumb/5/51/Aegean_cat.jpg/100px-Aegean_cat.jpg"
}]

以上是一个简短的片段。我正在尝试使用getJson加载此JSON文件并将其格式化为可排序的表。我可以将表格渲染到屏幕上,但不能完全使我的排序功能起作用。我知道sort函数适用于常规HTML表,我认为它与我的整体方法有关,因为我是前端方面的新手。代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html;charset=Windows-1252">
<style type="text/css">
    table {
        border-collapse: collapse;
        border: none;
    }
    th,
    td {
        border: 1px solid black;
        padding: 4px 16px;
        font-family: Times New Roman;
        font-size: 24px;
        text-align: left;
    }
    th {
        background-color: #C8C8C8;
        cursor: pointer;
    }
</style>
</head>
<body>
<div id="catTable"></div>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
var cats, asc1 = 1,
        asc2 = 1,
        asc3 = 1;
    window.onload = function () {
        cats = document.getElementById("cats");
    }

    function sort_table(tbody, col, asc) {
        var rows = tbody.rows,
            rlen = rows.length,
            arr = new Array(),
            i, j, cells, clen;
        // fill the array with values from the table
        for (i = 0; i < rlen; i++) {
            cells = rows[i].cells;
            clen = cells.length;
            arr[i] = new Array();
            for (j = 0; j < clen; j++) {
                arr[i][j] = cells[j].innerHTML;
            }
        }
        // sort the array by the specified column number (col) and order (asc)
        arr.sort(function (a, b) {
            return (a[col] == b[col]) ? 0 : ((a[col] > b[col]) ? asc : -1 *   asc);
        });
        // replace existing rows with new rows created from the sorted array
        for (i = 0; i < rlen; i++) {
            rows[i].innerHTML = "<td>" + arr[i].join("</td><td>") + "</td>";
        }
    }  
$.getJSON('cats.json', function(cats) {
    var output="<table>";
        output+="<thead>"
        output+="<tr>";
        output+="<th> HeadShot </th>";
        output+= '<th onclick="sort_table(cats, 0, asc1); asc1 *= -1; asc2 =   1; asc3 = 1;">Breed</th>';
        output+= '<th onclick="sort_table(cats, 1, asc2); asc2 *= -1; asc3 = 1; asc1 = 1;">Country</th>';
        output+= '<th onclick="sort_table(cats, 2, asc3); asc3 *= -1; asc1 = 1; asc2 = 1;">CoffeePreference</th>';
        output+="</tr>";
        output+="</thead>";

    for (var i in cats) {
        output+="<tbody id = 'cats'>"; 

        output+="<tr>";
        output+="<td><img src='" + cats[i].picture+"' alt='cat picture'>     </td>";
        output+="<td>" + cats[i].breed + "</td>";
        output+="<td>" + cats[i].country + "</td>";
        output+="<td>" + cats[i].coffeePreference + "</td>";
        output+="</tr>";
        output+="</tbody>"; 

    }
    output+="</table>";
    document.getElementById("catTable").innerHTML=output;



 });


</script>
</body>
</html>

任何帮助或指示。非常感谢。

2 个答案:

答案 0 :(得分:6)

https://www.datatables.net/

这将自动从JSON生成表并对其进行排序。具体设置的一个很好的起点是:

https://www.datatables.net/examples/server_side/object_data.html

您可以在没有“processing”和“serverSide”的情况下使用它,并将“ajax”部分替换为您的JSON文件。

修改

以下是数据集的基本实现:http://jsbin.com/kajina/1/edit?html,js,output

修改2

要使用远程数据源,您需要将{data:cats}属性替换为{ajax:“cats.json”}。这将使DataTables为您运行$ .getJSON()函数并从服务器获取数据。

此处有多种类型的数据源https://www.datatables.net/examples/data_sources/

此外,对于大型JSON文件,我建议考虑分页(服务器过滤数据并一次只向您发送一页项目)。请参阅此处的文档:https://www.datatables.net/examples/server_side/simple.html

答案 1 :(得分:1)

可以帮助您入门:

我们的想法是创建一个行对象数组,其中每个对象都有一个表的每个标题的属性,该属性具有该行的关联数据点。

然后可以根据特定标题对行对象数组进行排序(使用sortByKey函数)。

然后,生成的排序行对象数组可以按排序顺序呈现回现有表。

如果可能的话,可能更容易保持表示表的对象进行排序和渲染,而不是从表中获取数据。

未经测试,但可能会让球滚动。祝你好运!

    /**
    *Sort a table element based on a header value
    *@param {object} table The table containing data to be sorted
    *@param {string|number} The column used to sort the rows
    *@param {boolean|null} Determines if the sort should be in reverse order
    */
    var sortTable = function sortTable (table, sortColumn, reverse) {
        var tArr = [];
        var tHeaders = table.tHead.getElementsByTagName('th');
        var tRows = table.tBody.getElementsByTagName('tr');
        var sArr;

        //Create an array of header titles for the table
        //In the order they appear in the header row
        var headers = table.tHead.getElementsByTagName('th');

        //Convert to actual array
        headers = [].slice.call(headers);

        //Replace objects with text
        headers = headers.map(function getHeaderText(header) {
            return header.innerText || header.textContent;
        });

        //Create a row object for each row of data in the table
        //having a property for each column of the table and
        //a corresponding value for that column
        tRows.forEach(function applyRows(row) {
            var col_ct = headers.length - 1;
            var rowObj = {};

            //Create an array of data values in the order they appear
            //in the row
            var data = row.getElementsByTagName('td');
            data = [].slice.call(data);
            data = data.map(function getDataText(data) {
                return data.innerText || data.textContent;    
            });

            //The number of headers should match the number
            //of data points in the row
            if (headers.length !== data.length) {
                alert('Column mismatch');
            }

            //Set header property value to associated data for this row
            while (col_ct) {
                rowObj[headers[col_ct]] = data[col_ct];
                col_ct--;
            }

            //Add the row to the table array
            tArr.push(rowObj);
         });

         //Now tArr contains all rows of your table
         //use sortObjs to sort rows based on particular property
         sArr = tArr.sort(sortByKey(sortColumn, reverse));

         //Then unfold the sorted object to rebuild the table
         sArr.forEach(function buildTableRow(rowObj) {
           //Some function that builds table rows and renders them
           //Rows will then be rendered in sorted order
     });

     };

/**
*Sort an array of objects based on a key
*@param {string|number} field The property to sort by
*@param {boolean} reverse The direction of sort
*@return {object} Params for sort
*/
var sortByKey = function sortByKey(key, reverse) {

    /**
    *Return the value of a given key
    *@param {object} o The object to sort
    *@return {string|number|object} The value of the key
    */
    var value = function (o) {
        return o[key];
    };

    var reverse = (reverse) ? -1 : 1;
    return function (a, b) {
        return a = value(a), b = value(b), reverse * ((a > b) - (b > a));
    };

};