Mike Resoli
Mike Resoli

Reputation: 967

Turning HTML tables in object structures

I have two tables that I need to extract data from, and turn this into a javascript object structure, ideally like the following: Data --> Table --> Rows --> Cells. The tables are in the following format.

enter image description here

My javascript and jQuery so far has not had the desired effect:

$(document).ready(function(){
    gatherData();
});

function gatherData(){
    data = [];

    tables = $('.before').find('table');

    $(tables).each(function(index){
        var table = [];
        var rows = [];
        var headRow = $(this).find('tr:first');
        var names = [];
        $(headRow).find('td').each(function(){
            var name = $(this).text();
            names.push(name)
        });

        $(this).find('tr').each(function(index){
            if (index != 0){
                rows.push({rowNum: index})
            }
        })
        table.push(names)       
        table.push({rows: rows})
        console.log(table)

        data.push({table: index})
    });
}

Here is a jsfiddle I have created.

Upvotes: 1

Views: 39

Answers (1)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167192

You actually missed a lot of starting <tr>s.

And you need to use this instead of index:

data.push({table: table});

Now it outputs:

Object {table: Array[2]}
  table: Array[2]

Upvotes: 1

Related Questions