Home > Web Front-end > JS Tutorial > body text

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

Barbara Streisand
Release: 2024-10-30 04:53:02
Original
425 people have browsed it

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);
});
Copy after login

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] ) {
...
}
Copy after login

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
});
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!