将表转换为数组

我已经看过很多关于如何将数组转换成表格的post,但其他方面的数据并不多。 我想找个像这样的桌子:

Functional Category Brand Name When Obtained How Obtained How Often Worn Where Made Has a Graphic
T-Shirt threadless Last 3 Months Purchased Monthly India Yes
T-Shirt RVCA 2 Years Ago Purchased Bi-Monthly Mexico Yes

进入这样的数组:

 var tableData = [ { category: "T-shirt", brandName: "threadless", whenObtained: "Last 3 Months", howObtained: "Purchased", howOftenWorn: "Monthly", whereMade: "India", hasGraphic: "Yes" }, { category: "T-shirt", brandName: "RVCA", whenObtained: "2 Years Ago", howObtained: "Purchased", howOftenWorn: "Bi-Monthly", whereMade: "Mexico", hasGraphic: "Yes" } ] 

我希望使用jQuery,并想知道最好的方法是什么。

以下应该这样做!

 var array = []; var headers = []; $('#dataTable th').each(function(index, item) { headers[index] = $(item).html(); }); $('#dataTable tr').has('td').each(function() { var arrayItem = {}; $('td', $(this)).each(function(index, item) { arrayItem[headers[index]] = $(item).html(); }); array.push(arrayItem); }); 

在这里查看jsFiddle

 var table = document.getElementById( "dataTable" ); var tableArr = []; for ( var i = 1; i < table.rows.length; i++ ) { tableArr.push({ category: table.rows[i].cells[0].innerHTML, brandName: table.rows[i].cells[1].innerHTML, whenObtained: table.rows[i].cells[2].innerHTML, howObtained: table.rows[i].cells[3].innerHTML, howOftenWorn: table.rows[i].cells[4].innerHTML, whereMade: table.rows[i].cells[5].innerHTML, hasGraphic: table.rows[i].cells[6].innerHTML }); } 

所以我做的是选择所有的tr元素并迭代它们。 接下来我检查以确保我没有看到元素。 然后我使用cols数组来填充对象。 这可能更简单(2d数组),但我使用cols因为这是你的输出。

 var i, items, item, dataItem, data = []; var cols = [ "category", "brandName", "whenObtained", "howObtained", "howOftenWorn", "whereMade", "hasGraphic" ]; $("#dataTable tr").each(function() { items = $(this).children('td'); if(items.length === 0) { // return if this tr only contains th return; } dataItem = {}; for(i = 0; i < cols.length; i+=1) { item = items.eq(i); if(item) { dataItem[cols[i]] = item.html(); } } data.push(dataItem); }); 

请看这里的例子。 我在下面列出了相关代码:

 $(function() { var $rows= $("#tableName tbody tr"); var data = []; $rows.each(function(row, v) { $(this).find("td").each(function(cell, v) { if (typeof data[cell] === 'undefined') { data[cell] = []; } data[cell][row] = $(this).text(); }); }); console.log(data); });