Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I've created an application for converting a table to JSON object, the application is working fine but the problem is that an empty array is first appearing for the body key. can anyone tell me some

{"head":["Person Name","Person Name","Points","Price","Tax"],"body":[[],["Jill","Smith","50","150","41"],["Eve","Jackson","94","250","81"],["John","Doe","80","950","412"],["Adam","Johnson","67","750","941"]]} 

my script is given below

$('#convert-table').click( function() {
    try{
var myTable = [];
var myTr =[];
$('#example-table tr').each(function (i, tr) {
    var myTd =[];
    $('th', tr).each(function(j, th) {
          myTr.push($.trim(th.innerHTML));
    });

    $('td', tr).each(function(j, td) {
        if(td.innerHTML.indexOf("span") != -1){
            var text = $(this).closest('td').find('span').text();
            myTd.push($.trim(text));
        }
        else{
            myTd.push($.trim(td.innerHTML));
        }
    });


    myTable.push(myTd);
});

var headObj ={
    head:myTr,
    body:myTable
};

jsfiddle

share|improve this question
add comment

2 Answers

up vote 4 down vote accepted

Try to use condition to check if an array is not empty

Updated: Because for the first TR you have only th instead of td that's why your array is empty.


For instance

if(myTd.length > 0)
      myTable.push(myTd);
share|improve this answer
add comment

The issue is because in the first <tr> you only have <th> tags, yet you still push to myTable, so that's where the empty array is coming from.

only push to myTable when you have actual <td> to push to it.

You could do this by checking the current row doesn't have any <tr> tags in it or checking that the myTr array has already been pushed to, indicating you've already passed the row with the <th> in it.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.