9

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
ayyp
  • 6,590
  • 4
  • 33
  • 47
  • similar question http://stackoverflow.com/questions/1872485/iterate-through-html-table-using-jquery-converting-the-data-in-the-table-into-j – kamui Nov 22 '11 at 17:52
  • @JamesMontagne I was unsure as to even begin going about this as it is above and beyond my current skill level. Therefore, I have, unfortunately, not been able to try anything. – ayyp Nov 22 '11 at 17:53
  • What if I'm not looking to do it in JSON though? – ayyp Nov 22 '11 at 17:53

5 Answers5

15

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

Rich O'Kelly
  • 41,274
  • 9
  • 83
  • 114
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
    });
}
Will
  • 19,661
  • 7
  • 47
  • 48
1

See here for an example. I've included the relevant code below:

$(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);
});
James Johnson
  • 45,496
  • 8
  • 73
  • 110
1

So what I did is select all the tr elements and iterate over them. Next i check to make sure I am not looking at th elements. Then i use the cols array to populate the objects. This could have been simpler (2d array) but I use cols since that is what you had as your output.

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);
});
John Kalberer
  • 5,690
  • 1
  • 23
  • 27
0

There's a good tool: $(table).map, but saldly, it always return flatten array, no matter how many nested .map() is inside (you need two: one for rows and one for cells).

So let's use jQuery.map for tables and tr's and object.map() for cells, having 2nd nesting level return an array

function t2a (tabble){
return $.map($(tabble),function(el,i) {
    return $.map($(el).find('tr'),function(el,i) {
        return [
            $(el).find('td').map(function() {
                return $(this).text();
            }).get()
        ];
    });
});
}
fathergorry
  • 399
  • 2
  • 12