简体   繁体   中英

Store table in 2d array jquery

I'm trying to store a table in a 2d array so that each item in the array will be an array containing all the cells in a row.

I'm using:

var tRow = [];
var tRows = [];
tab = document.getElementById('table'); 

for(var r = 0 ; r < tab.rows.length ; r++) {
    for (var c=0; c < tab.rows[r].cells.length; c++){
        tRow[c] = tab.rows[r].cells[c].innerHTML;                       
    }

    tRows.push(tRow);
}

this just gives me the last row item in 20 places rather than each item in the table at its respective index. So, for this table:

<tr> 
 <td>Row 1 cell 1</td>
 <td>Row 1 cell 2</td>
 <td>Row 1 cell 3</td>
 <td>Row 1 cell 4</td>
</tr>
<tr>
 <td>Row 2 cell 1</td>
 <td>Row 2 cell 2</td>
 <td>Row 2 cell 3</td>
 <td>Row 2 cell 4</td>
</tr>

tRows will be:

tRows =[ [Row 2 cell 1,Row 2 cell 2,Row 2 cell 3,Row 2 cell 4] , [Row 2 cell 1,Row 2 cell 2,Row 2 cell 3,Row 2 cell 4] ]

instead of:

tRows =[ [Row 1 cell 1,Row 1 cell 2,Row 1 cell 3,Row 1 cell 4] , [Row 2 cell 1,Row 2 cell 2,Row 2 cell 3,Row 2 cell 4] ]

I don't know what I'm doing wrong. Please help.

You can do this with two map() functions.

 var tRows = $('tr').map(function() { return [$(this).find('td').map(function() { return $(this).text() }).get()] }).get() console.log(tRows)
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td>Row 1 cell 1</td> <td>Row 1 cell 2</td> <td>Row 1 cell 3</td> <td>Row 1 cell 4</td> </tr> <tr> <td>Row 2 cell 1</td> <td>Row 2 cell 2</td> <td>Row 2 cell 3</td> <td>Row 2 cell 4</td> </tr> </table>

Your issue is you need a new tRow array for each iteration of outer loop.

Just move var tRow = []; inside that row loop

 var tRows = []; tab = document.getElementById('table'); for (var r = 0; r < tab.rows.length; r++) { var tRow = [];// start new row array for (var c = 0; c < tab.rows[r].cells.length; c++) { tRow[c] = tab.rows[r].cells[c].innerHTML; } tRows.push(tRow); } console.log(tRows);
 <table id="table"> <tr> <td>Row 1 cell 1</td> <td>Row 1 cell 2</td> <td>Row 1 cell 3</td> <td>Row 1 cell 4</td> </tr> <tr> <td>Row 2 cell 1</td> <td>Row 2 cell 2</td> <td>Row 2 cell 3</td> <td>Row 2 cell 4</td> </tr> </table>

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