Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

javascript - Convert Table to an Array

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>

Into an array like this:


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"
    }
]

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The following should do it!

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);
});

See here for jsFiddle


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...