1

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

2 Answers 2

4

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.