-1

Can anyone help me on this, I have the json data that i want to convert into table using javascript or jquery. Here's my sample json data:

{"company_name":"McDonalds","address":"John Street","city":"San Antonio","noemployee":"100"}

I want the table output should look like this:

    Company Name  Address  City          Noemployee
    McDonaldsJohn Street   San Antonio   100

Just to clarify "company_name":"McDonalds" = <thead><tr><th>Company Name</th></tr></thead><tbody><tr><td>McDonalds</td></tr></tbody>

Cris
  • 437
  • 2
  • 5
  • 15

2 Answers2

1

Take a look at jQuery datatables plugin or jQgrid plugin

Fseee
  • 2,476
  • 9
  • 40
  • 63
0

You can use lodash to do this

var d = {"company_name":"McDonalds","address":"John Street","city":"San Antonio","noemployee":"100"},

keys = _.keys(d), //Fetching the keys

thead = _.reduce(keys, function(s,i) { return s + "<th>" + i + "</th>"; }, ''),
thead = "<thead><tr>"+thead+"</tr></thead>",

tbody = _.reduce(keys, function(s,i) { return s + "<td>" + d[i] + "</td>"; }, ''),
tbody = "<tbody><tr>" + tbody + "</tr></tbody>",

table = "<table>" + thead+tbody+"</table>";

_.reduce takes an array and converts it into a single element. Go through the docs to learn how it works.

Here is the jQuery version

var d = {"company_name":"McDonalds","address":"John Street","city":"San Antonio","noemployee":"100"},

var t='',b=''; 

$.each(d, function(v) { t += "<th>" + v + "</th>"; }); 

t = "<thead>"+t+"</thead>"; 

$.each(d, function(v) { b += "<td>" + d[v] + "</td>"; }); 

b = '<tbody>'+b+'</tbody>'; 

var tab = "<table>" + t + b + "</table>";
Prathik Rajendran M
  • 1,152
  • 8
  • 21