简体   繁体   中英

Creating 3 table columns from JSON using jQuery

Im making a table from JSON using jQuery but i'm struggling to get the last column to render due to the structure of the JSON, also the other columns do not quite display the way i was looking for.

I've tried using $.each and a for loop for the last column but nothing i've tried has fixed it.

The JSON looks like:

     {
         "countries": ["US", "UK", "France", "Germany"],
         "months": ["May-2012", "June-2012", "July-2012"],
         "types": [{
             "type": "Democrat"
         }, {
             "type": "Republican"
         }, {
             "type": "Green"
         }, ]
     }

And my jQuery is:

 var target = $('#targettable');
 target.empty();

 $(target).append($('<tr />')
     .append($('<th />').text('Countries'))
     .append($('<th />').text('Months'))
     .append($('<th />').text('Types')));

 $('<tr>')
     .append($('<td>', {
     'text': myJSON.countries
 }))
     .append($('<td>', {
     'text': myJSON.months
 }))

     .append($('<td>', {
     'text': myJSON.types.type
 }))
     .appendTo(target);

i made a fiddle of it http://jsfiddle.net/ZukKR/

The last column doesnt show at all and the other 2 arent displaying as a wanted, i was thinking it would create a row per item.

So basically a list of countries in one column, a list of months in the next column and a list of types in the last column. Not sure what else i could try?

Try this ( demo ):

myJSON = {
    "countries": ["US", "UK", "France", "Germany"],
    "months": ["May-2012", "June-2012", "July-2012", "Aug-2012"],
    "types": [{
            "type": "Democrat"
        }, {
            "type": "Republican"
        }, {
            "type": "Green"
        }, {
            "type": "Purple"
        }
    ]
};

var target = $('#targettable'),
    table = '<tr><th>Countries</th><th>Months</th><th>Types</th></tr>';

for (var i = 0; i < myJSON.countries.length; i++) {
    table += '<tr>' +
        '<td>' + myJSON.countries[i] + '</td>' +
        '<td>' + myJSON.months[i] + '</td>' +
        '<td>' + myJSON.types[i].type + '</td>' +
        '</tr>';
}

target.html(table);

Note:

  • There will be a js error if the number of entries do not match, I had to add an extra month and type entry.
  • Using append for every JSON entry makes building the table much slower, due to lots of DOM interaction, so it is better to build a string, then just apply the table once.

It is a little less convoluted than you may have originally thought -

$(target).append($('<tr />')
         .append($('<th />').text('Countries'))
         .append($('<th />').text('Months'))
         .append($('<th />').text('Types')));

     for (var i = 0; i < myJSON.countries.length; i++) {
         $(target).append('<tr />');
         $('tr:last').append($('<td>', {
             'text': myJSON.countries[i]
         }));
         $('tr:last').append($('<td>', {
             'text': myJSON.months[i]
         }));
         $('tr:last').append($('<td>', {
             'text': myJSON.types[i].type
         }));
     }

Here is an example - http://jsfiddle.net/ZukKR/2/

There are many things that you can do here to make this more efficient - saving the string and writing it out all at once, shortening the append statement to make it one string, and so on.

Here you go:

myJSON = {
    "countries": ["US", "UK", "France", "Germany"],
    "months": ["May-2012", "June-2012", "July-2012"],
    "types": [{
        "type": "Democrat"
    }, {
        "type": "Republican"
    },{
        "type": "Green"
    },
    ]
}


var target = $('#targettable');
target.empty();

$(target).append($('<tr />')
    .append($('<th />').text('Countries'))
    .append($('<th />').text('Months'))
    .append($('<th />').text('Types'))
);

types = [];
for(var i = 0 ; i < myJSON.types.length; i ++){
    types.push(myJSON.types[i]['type']);
}

$('<tr>')
    .append($('<td>', {
        'text': myJSON.countries
    }))
    .append($('<td>', {
        'text': myJSON.months
    }))              
    .append($('<td>', {
        'text': types
    }))
    .appendTo(target);

In this jsfiddle

- no errors in the console.
- the headers of the columns are dynamic
- the table extends with the longest column
myJSON = {
    "countries": ["US", "UK", "France", "Germany"],
    "months": ["May-2012", "June-2012", "July-2012","well","this"],
    "types": [
        {
            "type": "Democrat"
        }, {
            "type": "Republican"
        }, {
            "type": "Green"
        }
    ]
}    
var target = $('#targettable');
var longest =null;
var thead = $('<tr />');
$.each(myJSON, function(index, value){
    if(longest === null) longest = index;
    else if(myJSON[longest].length < myJSON[index].length) longest = index;

    thead.append($("<th>").text(index));
});

target.find("thead").append(thead);

for (var i = 0; i < myJSON[longest].length; i++) {
    $(target).append('<tr />');
    $('tr:last').append($('<td>', {
        'text': myJSON.countries[i]?myJSON.countries[i]:""
    }));
    $('tr:last').append($('<td>', {
        'text': myJSON.months[i]?myJSON.months[i]:""
    }));
    $('tr:last').append($('<td>', {
        'text': myJSON.types[i] && myJSON.types[i].type?myJSON.types[i].type:""
    }));
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM