[code snippet] Populate a table from an array (JQuery)

Ever returned a massive array from json? Want to pre render the table to reduce dom manipulation and just populate the data?

Well this can be used for tables and with a modification a table made from DIVs (If you really don’t want to use tables for what they are used for!)

Basically I got asked how do you do this using JQuery, it really makes it simple doesn’t it.

A simple nested loop, if you can beat it for performance please post I want to know!

var newarray = [["One","Two","Three"],
                ["One 2nd","Two 2nd","Three 2nd"],
                ["One 3rd","Two 3rd","Three 3rd"]];
$('#foo tr').each(
    function(i) {$(this).find('td').each(
        function(j) {
            $(this).html(newarray[i][j]);
        });
    });
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s