Home >Web Front-end >JS Tutorial >How Can I Efficiently Convert JSON Arrays to HTML Tables Using jQuery?

How Can I Efficiently Convert JSON Arrays to HTML Tables Using jQuery?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-30 05:15:03989browse

 How Can I Efficiently Convert JSON Arrays to HTML Tables Using jQuery?

Effortless Conversion of JSON Arrays to HTML Tables Using jQuery

When faced with the task of converting an array of JSON objects into an HTML table, the complexity of the process can be daunting. Fortunately, jQuery simplifies this process considerably.

Leveraging jQuery to Automate Table Creation

The provided jQuery code streamlines the conversion process by iterating through each JSON object in the array and dynamically generating the corresponding table rows and cells:

<code class="javascript">$.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);
});</code>

Excluding Specific Fields (Optional)

To exclude specific fields from the table, simply create an object with their names as keys and true/false values to indicate inclusion or exclusion:

<code class="javascript">var expected_keys = { key_1 : true, key_2 : true, key_3 : false, key_4 : true };</code>

Then, wrap the tbl_row = line with the following check:

<code class="javascript">if ( ( k in expected_keys ) && expected_keys[k] ) {
...
}</code>

Injection-Free Alternative

For a more isolated approach, consider this DOM-based solution:

<code class="javascript">$.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
});</code>

The above is the detailed content of How Can I Efficiently Convert JSON Arrays to HTML Tables Using jQuery?. 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