Nicholas Hazel Nicholas Hazel - 1 month ago 11
jQuery Question

Convert a Multi-Dimensional Array to HTML Table

Playing with a quick concept. Hopefully the answer is pretty simple, my attempt is just failing here for some reason.

Let's say I have an array such as:

var items = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]];


And I'm trying to flip the data around, so it converts it into:

var items_converted = [[1,4,7,10],[2,5,8,11],[3,6,9,12]];


This much is completed. Now, with my new multidimensional array, I want to push each internal array's contents to an HTML table row:

<tr>
<td>1</td>
<td>4</td>
<td>7</td>
<td>10</td>
</tr>
<tr>
<td>...


Play here: http://jsfiddle.net/XDFd2/



I tried doing it with two
for-loops
, but it doesn't seem to be appending the
<tr>
or
</tr>
.

var items = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]];
var items_converted = [[1,4,7,10],[2,5,8,11],[3,6,9,12]];
var table = $('#table');

for(var i=0; i<items_converted.length; i++){
if(i==0){
table.append('<tr>');
}
for(var j=0; j<items_converted[i].length; j++){
table.append('<td>'+items_converted[i][j]+'</td>');
if(j===items_converted[0].length-1){
table.append('</tr');
}
}
}


I feel I'm missing something very simple here... perhaps the order that the loops are processing?

Any help is appreciated.

Play here: http://jsfiddle.net/XDFd2/


Answer

You're trying to use append() like document.write(). That's a wrong approach. You should look at the DOM starting at your table node and append nodes for each row and cell.

Basically a $('<tr>') to create a row, followed by an table.append() call to add it to the DOM. Likewise for the cells.

var items = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]];
var items_converted = [[1,4,7,10],[2,5,8,11],[3,6,9,12]];
var table = $('#table');
var row, cell;

for(var i=0; i<items_converted.length; i++){
     row = $( '<tr />' );
    table.append( row );
    for(var j=0; j<items_converted[i].length; j++){
        cell = $('<td>'+items_converted[i][j]+'</td>')
        row.append( cell );
    }
}

Fiddle