将表转换为数组 [英] Convert Table to an Array

查看:39
本文介绍了将表转换为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过很多关于如何将数组转换为表格的帖子,但几乎没有其他方法.我想要一张这样的桌子:

I have seen many posts about how to turn an array into a table, but not nearly as many going the other way. I'm looking to take a table like this:


<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>

变成这样的数组:


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,并且想知道解决此问题的最佳方法是什么.

I am looking to use jQuery for this and was wondering what the best way to go about this is.

推荐答案

以下应该做!

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见这里

这篇关于将表转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆