Convert JSON array to an HTML table in jQuery

前端 未结 15 881
温柔的废话
温柔的废话 2020-11-22 16:33

Is there a really easy way I can take an array of JSON objects and turn it into an HTML table, excluding a few fields? Or am I going to have to do this manually?

相关标签:
15条回答
  • 2020-11-22 16:39

    For very advanced JSON objects to HTML tables you can try My jQuery Solution that is based on this closed thread.

    var myList=[{"name": "abc","age": 50},{"name": {"1": "piet","2": "jan","3": "klaas"},"age": "25","hobby": "watching tv"},{"name": "xyz","hobby": "programming","subtable": [{"a": "a","b": "b"},{"a": "a","b": "b"}]}];
    
    // Builds the HTML Table out of myList json data from Ivy restful service.
     function buildHtmlTable() {
          addTable(myList, $("#excelDataTable"));
     }
    
    function addTable(list, appendObj) {
        var columns = addAllColumnHeaders(list, appendObj);
    
        for (var i = 0; i < list.length; i++) {
            var row$ = $('<tr/>');
            for (var colIndex = 0; colIndex < columns.length; colIndex++) {
                var cellValue = list[i][columns[colIndex]];
    
                if (cellValue == null) {
                    cellValue = "";
                }
    
                if (cellValue.constructor === Array)
                {
                    $a = $('<td/>');
                    row$.append($a);
                    addTable(cellValue, $a);
    
                } else if (cellValue.constructor === Object)
                {
    
                    var array = $.map(cellValue, function (value, index) {
                        return [value];
                    });
    
                    $a = $('<td/>');
                    row$.append($a);
                    addObject(array, $a);
    
                } else {
                    row$.append($('<td/>').html(cellValue));
                }
            }
            appendObj.append(row$);
        }
    }
    
    
    function addObject(list, appendObj) {
        for (var i = 0; i < list.length; i++) {
            var row$ = $('<tr/>');
    
            var cellValue = list[i];
    
            if (cellValue == null) {
                cellValue = "";
            }
    
            if (cellValue.constructor === Array)
            {
                $a = $('<td/>');
                row$.append($a);
                addTable(cellValue, $a);
    
            } else if (cellValue.constructor === Object)
            {
    
                var array = $.map(cellValue, function (value, index) {
                    return [value];
                });
    
                $a = $('<td/>');
                row$.append($a);
                addObject(array, $a);
    
            } else {
                row$.append($('<td/>').html(cellValue));
            }
            appendObj.append(row$);
        }
    }
    
    // Adds a header row to the table and returns the set of columns.
    // Need to do union of keys from all records as some records may not contain
    // all records
    function addAllColumnHeaders(list, appendObj)
    {
        var columnSet = [];
        var headerTr$ = $('<tr/>');
    
        for (var i = 0; i < list.length; i++) {
            var rowHash = list[i];
            for (var key in rowHash) {
                if ($.inArray(key, columnSet) == -1) {
                    columnSet.push(key);
                    headerTr$.append($('<th/>').html(key));
                }
            }
        }
        appendObj.append(headerTr$);
    
        return columnSet;
    }
    
    0 讨论(0)
  • 2020-11-22 16:39

    You could use a jQuery plugin that accepts JSON data to fill a table. jsonTable

    0 讨论(0)
  • 2020-11-22 16:40

    If you accept using another jQuery dependent tool, I would recommend using Tabulator. Then you will not need to write HTML or any other DOM generating code, while maintaining great flexibility regarding the formatting and processing of the table data.

    For another working example using Node, you can look at the MMM-Tabulator demo project.

    0 讨论(0)
  • 2020-11-22 16:43

    Converting a 2D JavaScript array to an HTML table

    To turn a 2D JavaScript array into an HTML table, you really need but a little bit of code :

    function arrayToTable(tableData) {
        var table = $('<table></table>');
        $(tableData).each(function (i, rowData) {
            var row = $('<tr></tr>');
            $(rowData).each(function (j, cellData) {
                row.append($('<td>'+cellData+'</td>'));
            });
            table.append(row);
        });
        return table;
    }
    
    $('body').append(arrayToTable([
        ["John","Slegers",34],
        ["Tom","Stevens",25],
        ["An","Davies",28],
        ["Miet","Hansen",42],
        ["Eli","Morris",18]
    ]));
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>


    Loading a JSON file

    If you want to load your 2D array from a JSON file, you'll also need a little bit of Ajax code :

    $.ajax({
        type: "GET",
        url: "data.json",
        dataType: 'json',
        success: function (data) {
            $('body').append(arrayToTable(data));
        }
    });
    
    0 讨论(0)
  • 2020-11-22 16:44

    One simple way of doing this is:

    var data = [{
      "Total": 34,
      "Version": "1.0.4",
      "Office": "New York"
    }, {
      "Total": 67,
      "Version": "1.1.0",
      "Office": "Paris"
    }];
    
    drawTable(data);
    
    function drawTable(data) {
    
      // Get Table headers and print
      var head = $("<tr />")
      $("#DataTable").append(head);
      for (var j = 0; j < Object.keys(data[0]).length; j++) {
        head.append($("<th>" + Object.keys(data[0])[j] + "</th>"));
      }
    
      // Print the content of rows in DataTable
      for (var i = 0; i < data.length; i++) {
        drawRow(data[i]);
      }
    
    }
    
    function drawRow(rowData) {
      var row = $("<tr />")
      $("#DataTable").append(row);
      row.append($("<td>" + rowData["Total"] + "</td>"));
      row.append($("<td>" + rowData["Version"] + "</td>"));
      row.append($("<td>" + rowData["Office"] + "</td>"));
    }
    table {
      border: 1px solid #666;
      width: 100%;
      text-align: center;
    }
    
    th {
      background: #f8f8f8;
      font-weight: bold;
      padding: 2px;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table id="DataTable"></table>

    0 讨论(0)
  • 2020-11-22 16:44

    A still shorter way

    $.makeTable = function (mydata) {
                if (mydata.length <= 0) return "";
               return $('<table border=1>').append("<tr>" + $.map(mydata[0], function (val, key) {
                    return "<th>" + key + "</th>";
                }).join("\n") + "</tr>").append($.map(mydata, function (index, value) {
                    return "<tr>" + $.map(index, function (val, key) {
                        return "<td>" + val + "</td>";
                    }).join("\n") + "</tr>";
                }).join("\n"));
            };
    
    0 讨论(0)
提交回复
热议问题