Home  >  Article  >  Web Front-end  >  How to Convert JSON Arrays into HTML Tables with jQuery, Including the Ability to Exclude Specific Fields?

How to Convert JSON Arrays into HTML Tables with jQuery, Including the Ability to Exclude Specific Fields?

Barbara Streisand
Barbara StreisandOriginal
2024-10-30 04:53:02426browse

How to Convert JSON Arrays into HTML Tables with jQuery, Including the Ability to Exclude Specific Fields?

Converting JSON Arrays to HTML Tables with jQuery

Transforming an array of JSON objects into an HTML table can be accomplished efficiently using jQuery.

Solution:

The provided jQuery code snippet converts an array of JSON objects into an HTML table, excluding specific fields:

<pre class="brush:php;toolbar:false">
$.getJSON(url , function(data) {
    var tbl_body = "";
    var odd_even = false;
    $.each(data, function() {
        var tbl_row = "";
        $.each(this, function(k , v) {
            tbl_row += "<td>"+v+"</td>";
        });
        tbl_body += "<tr class=\""+( odd_even ? "odd" : "even")+"\">"+tbl_row+"</tr>";
        odd_even = !odd_even;               
    });
    $("#target_table_id tbody").html(tbl_body);
});

To exclude specific keys, add this logic before the tbl_row = line:

var expected_keys = { key_1 : true, key_2 : true, key_3 : false, key_4 : true };
if ( ( k in expected_keys ) &amp;&amp; expected_keys[k] ) {
...
}

Alternatively, a more secure and DOM-friendly approach can be used:

<pre class="brush:php;toolbar:false">
$.getJSON(url , function(data) {
    var tbl_body = document.createElement("tbody");
    var odd_even = false;
    $.each(data, function() {
        var tbl_row = tbl_body.insertRow();
        tbl_row.className = odd_even ? "odd" : "even";
        $.each(this, function(k , v) {
            var cell = tbl_row.insertCell();
            cell.appendChild(document.createTextNode(v.toString()));
        });        
        odd_even = !odd_even;               
    });
    $("#target_table_id").append(tbl_body);   //DOM table doesn't have .appendChild
});

These methods allow you to easily convert JSON arrays into HTML tables, with the flexibility to exclude unwanted fields.

The above is the detailed content of How to Convert JSON Arrays into HTML Tables with jQuery, Including the Ability to Exclude Specific Fields?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn