Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...