2

I am trying to print a JSON array in a table. Here is my code. Any suggestions? Thanks in advance.

[
  {
    "id": 1,
    "name": "name1",
    "age": 10,
    "feedback": "feedback1"
  },
  {
    "id": 2,
    "name": "name2",
    "age": 90,
    "feedback": "feedback2"
  },
  {
    "id": 3,
    "name": "name3",
    "age": 30,
    "feedback": "feedback3"
  },
  {
    "id": 4,
    "name": "name4",
    "age": 50,
    "feedback": "feedback4"
  }
]

var fileName = "";

function GridLibrary(fileName) {
  this.fileName = fileName;

}
GridLibrary.prototype = {
  set_fileName: function(fileName) {
    this.fileName = fileName;
  },
  get_fileName: function() {
    return this.fileName;
  }
};

GridLibrary.prototype.display = function() {
  $.ajax({

    url: this.get_fileName(),
    error: function(that, e) {

      console.log(e);
    },
    success: function(data) {
      // printing the keys
      var Mytable = "<table>";
      $.each(data[0], function(key, value) {
        $('body').append('<tr><td id="div' + key + '" </td></tr>');
        $('#div' + key).append(key);
      });
      // printing the rest
      $.each(data, function(index, MyList) {
        $.each(MyList, function(key, value) {
          $('#div' + key).append(" " + MyList[key] + " ");
        });
      });
      Mytable += '</table>';
      $('body').append(Mytable);
    }
  });
};

the output is

 id 1 2 3 4
name name1 name2 name3 name4
age 10 90 30 50
feedback feedback1 feedback2 feedback3 feedback4

but I want it to be like

id  name  age  feedback
 1  name1  10  feedback1
 2  name2  90  feedback2
 3  name3  30  feedback3
 4  nanme4  50  feedback4

4 Answers 4

2

You could give this a try:

var table = [{
  "id": 1,
  "name": "name1",
  "age": 10,
  "feedback": "feedback1"
}, {
  "id": 2,
  "name": "name2",
  "age": 90,
  "feedback": "feedback2"
}, {
  "id": 3,
  "name": "name3",
  "age": 30,
  "feedback": "feedback3"
}, {
  "id": 4,
  "name": "name4",
  "age": 50,
  "feedback": "feedback4"
}];

function addTable(tableData) {

  var table = $('<table>');

  var tableHeading = $('<tr>');


  for (var title in tableData[0]){
    if (! tableData[0].hasOwnProperty(title))
        continue;

    var headingColumn = $('<th>'+ title +'</th>');
    headingColumn.appendTo(tableHeading);
  }

  tableHeading.appendTo(table);

  tableData.forEach((rowData)=>{

    var row  = $('<tr>');

    for (var columnData in rowData) {
      if (! rowData.hasOwnProperty(columnData))
        continue;

      var column = $('<td>' + rowData[columnData] + '</td>');

      column.appendTo(row);
    }

    row.appendTo(table);

  });

  table.appendTo('body');
}

addTable(table);

Fiddle: https://jsfiddle.net/41g8g9Lc/1/

Be aware this doesn't check to ensure number of columns is same in each row. This kind of handling can be added if required.

Sign up to request clarification or add additional context in comments.

Comments

1

I usually do something like the the following, You can just replace the json array with your own:

Live Example

HTML:

<h2>An Example of Turning an Array of Objects into a Html Table</h2>

<div id="left">&nbsp;</div>
<div id="results"></div>
<div id="right">&nbsp;</div>

CSS(Optional):

body {
  background: gray;
}

#results,
#left,
#right {
  float: left;
}

#left {
  width: 33.33%;
}

#right {
  width: 33.3%;
}

#results {
  width: 33.33%;
}

h2{
  font-family:georgia;
  margin-left: auto;
  margin-right: auto;
  text-align: center;
  background-color: teal;
  color: #f0ffff;
}

td,
th {
  border: black solid 1px;
  padding: 5px;
}

td {
  background-color: teal;
  color: white;
}

th {
  background-color: blue;
  color: white;
  font-family: georgia;
}

JavaScript:

var json = [{

  "firstname": "Larry",
  "lastname": "Lane",
  "phone1": "111-111-1111"

}, {
  "firstname": "Gypsy",
  "lastname": "Lane",
  "phone1": "111-111-1111"

}];

//array to hold the html for the table
var html = [];

//add the opening table and tablebody tags
html.push("<table>\n<tbody>");


//begin adding the table headers

html.push("<tr>");

//loop through the property names of the first object
for(var propertyNames in json[0]){//begin for in loop

  html.push("<th>" + propertyNames  + "</td>");

}//end for in loop

html.push("</tr>");

//loop through the array of objects
json.forEach(function(item) { //begin forEach

  //add the opening table row tag
  html.push("<tr>");

  //loop though each of the objects properties
  for (var key in item) { //begin for in loop

    //append the table data containing the objects property value
    html.push("<td>" + item[key] + "</td>");

  } //end for in loop

  //add the closing table row tag
  html.push("</tr>");

}); //end forEach

//add the closing table and table body tags
html.push("<table>\n</tbody>");

//testing display of results
document.getElementById("results").innerHTML = html.join("");

1 Comment

This code makes me cringe for two reasons. 1. js object keys are unordered, each row could have columns in a different order, if you always iterated on json[0] at least you would get a consistent order though not predictable. 2. Concatenating text and html (like: "<td>" + item[key] + "</td>") leads to encoding problems and injection vulnerabilities. Since the question asks about jQuery, $('<td>').text(item[key]) is a better suggestion than sending some down the (faster but buggy) array of string path.
0

You're using two different methodologies to output your markup.

If you're going to use string concatenation, use it for the entire table. The point is, you're appending the <table></table> body after you create the rows and cells.

Not only that, but repeatedly updating the markup on the page for every cell is simply poor practice and very non-performant.

Comments

0

You're making a new <tr> for each <td> while the keys and data points need to be on the same <tr>

add something like this:

   $('body').append('<tr id="keys"></tr>');
   $('body tr.keys').append('<td id="div' + key + '" </td>');

and then you'd need to make a new table row for each set of data points to append to the table, then loop through the data to create the <td>s.

1 Comment

Larry Lane's example gives the full code for what I mean, it should be easy to adapt for your situation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.