0

Im making a table from JSON using jQuery but i'm struggling to get the last column to render due to the structure of the JSON, also the other columns do not quite display the way i was looking for.

I've tried using $.each and a for loop for the last column but nothing i've tried has fixed it.

The JSON looks like:

     {
         "countries": ["US", "UK", "France", "Germany"],
         "months": ["May-2012", "June-2012", "July-2012"],
         "types": [{
             "type": "Democrat"
         }, {
             "type": "Republican"
         }, {
             "type": "Green"
         }, ]
     }

And my jQuery is:

 var target = $('#targettable');
 target.empty();

 $(target).append($('<tr />')
     .append($('<th />').text('Countries'))
     .append($('<th />').text('Months'))
     .append($('<th />').text('Types')));

 $('<tr>')
     .append($('<td>', {
     'text': myJSON.countries
 }))
     .append($('<td>', {
     'text': myJSON.months
 }))

     .append($('<td>', {
     'text': myJSON.types.type
 }))
     .appendTo(target);

i made a fiddle of it http://jsfiddle.net/ZukKR/

The last column doesnt show at all and the other 2 arent displaying as a wanted, i was thinking it would create a row per item.

So basically a list of countries in one column, a list of months in the next column and a list of types in the last column. Not sure what else i could try?

4 Answers 4

1

Here you go:

myJSON = {
    "countries": ["US", "UK", "France", "Germany"],
    "months": ["May-2012", "June-2012", "July-2012"],
    "types": [{
        "type": "Democrat"
    }, {
        "type": "Republican"
    },{
        "type": "Green"
    },
    ]
}


var target = $('#targettable');
target.empty();

$(target).append($('<tr />')
    .append($('<th />').text('Countries'))
    .append($('<th />').text('Months'))
    .append($('<th />').text('Types'))
);

types = [];
for(var i = 0 ; i < myJSON.types.length; i ++){
    types.push(myJSON.types[i]['type']);
}

$('<tr>')
    .append($('<td>', {
        'text': myJSON.countries
    }))
    .append($('<td>', {
        'text': myJSON.months
    }))              
    .append($('<td>', {
        'text': types
    }))
    .appendTo(target);
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for this, it's the only one i actually got kind of working, the only thing is it just lists all the items in a line oppose to putting them on one a new line each, is there an easy way of adding a <br/> after each item?
Yeah sure :) types.push(myJSON.types[i]['type'] + "<br />");
Although, it may be worth adding new rows to the table if thats what you are going for :)
1

Try this (demo):

myJSON = {
    "countries": ["US", "UK", "France", "Germany"],
    "months": ["May-2012", "June-2012", "July-2012", "Aug-2012"],
    "types": [{
            "type": "Democrat"
        }, {
            "type": "Republican"
        }, {
            "type": "Green"
        }, {
            "type": "Purple"
        }
    ]
};

var target = $('#targettable'),
    table = '<tr><th>Countries</th><th>Months</th><th>Types</th></tr>';

for (var i = 0; i < myJSON.countries.length; i++) {
    table += '<tr>' +
        '<td>' + myJSON.countries[i] + '</td>' +
        '<td>' + myJSON.months[i] + '</td>' +
        '<td>' + myJSON.types[i].type + '</td>' +
        '</tr>';
}

target.html(table);

Note:

  • There will be a js error if the number of entries do not match, I had to add an extra month and type entry.
  • Using append for every JSON entry makes building the table much slower, due to lots of DOM interaction, so it is better to build a string, then just apply the table once.

Comments

1

It is a little less convoluted than you may have originally thought -

$(target).append($('<tr />')
         .append($('<th />').text('Countries'))
         .append($('<th />').text('Months'))
         .append($('<th />').text('Types')));

     for (var i = 0; i < myJSON.countries.length; i++) {
         $(target).append('<tr />');
         $('tr:last').append($('<td>', {
             'text': myJSON.countries[i]
         }));
         $('tr:last').append($('<td>', {
             'text': myJSON.months[i]
         }));
         $('tr:last').append($('<td>', {
             'text': myJSON.types[i].type
         }));
     }

Here is an example - http://jsfiddle.net/ZukKR/2/

There are many things that you can do here to make this more efficient - saving the string and writing it out all at once, shortening the append statement to make it one string, and so on.

3 Comments

Thanks, how would i handle this if i didn't know how which column was going to be the longest, in this example it will only go to the length of Countries, but what if types was larger? Is there a way of safeguarding against this?
At the moment i'm getting an error if i use anything other than types in my for loop, but if i have more values in my date column they're cut off.
You would have to check all lengths for the longest length and then loop for that. You could create a function to test all lengths and return the longest.
1

In this jsfiddle

- no errors in the console.
- the headers of the columns are dynamic
- the table extends with the longest column
myJSON = {
    "countries": ["US", "UK", "France", "Germany"],
    "months": ["May-2012", "June-2012", "July-2012","well","this"],
    "types": [
        {
            "type": "Democrat"
        }, {
            "type": "Republican"
        }, {
            "type": "Green"
        }
    ]
}    
var target = $('#targettable');
var longest =null;
var thead = $('<tr />');
$.each(myJSON, function(index, value){
    if(longest === null) longest = index;
    else if(myJSON[longest].length < myJSON[index].length) longest = index;

    thead.append($("<th>").text(index));
});

target.find("thead").append(thead);

for (var i = 0; i < myJSON[longest].length; i++) {
    $(target).append('<tr />');
    $('tr:last').append($('<td>', {
        'text': myJSON.countries[i]?myJSON.countries[i]:""
    }));
    $('tr:last').append($('<td>', {
        'text': myJSON.months[i]?myJSON.months[i]:""
    }));
    $('tr:last').append($('<td>', {
        'text': myJSON.types[i] && myJSON.types[i].type?myJSON.types[i].type:""
    }));
};

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.