将表转换为数组

ayy*_*yyp 6 javascript arrays jquery html-table

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


<table id="dataTable">
    <tr>
        <th>Functional Category</th>
        <th>Brand Name</th>
        <th>When Obtained</th>
        <th>How Obtained</th>
        <th>How Often Worn</th>
        <th>Where Made</th>
        <th>Has a Graphic</th>
    </tr>
    <tr>
        <td>T-Shirt</td>
        <td>threadless</td>
        <td>Last 3 Months</td>
        <td>Purchased</td>
        <td>Monthly</td>
        <td>India</td>
        <td>Yes</td>
    </tr>
    <tr>
        <td>T-Shirt</td>
        <td>RVCA</td>
        <td>2 Years Ago</td>
        <td>Purchased</td>
        <td>Bi-Monthly</td>
        <td>Mexico</td>
        <td>Yes</td>
    </tr>
</table>
Run Code Online (Sandbox Code Playgroud)

进入这样的数组:


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"
    }
]
Run Code Online (Sandbox Code Playgroud)

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

Ric*_*lly 13

以下应该做到这一点!

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);
});
Run Code Online (Sandbox Code Playgroud)

在这里看到jsFiddle

  • `$.each($('#dataTable th'), function(index, item) {` 可以是 `$('#dataTable th').each(function(index, item) {`. (2认同)

Wil*_*ill 6

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
    });
}
Run Code Online (Sandbox Code Playgroud)