How to generate HTML table by looping through object?

1505 views javascript
5

I have the following object:

var obj = {
    key1: value1,
    key2: value2,
    key3: value3,
    ......... //Dynamic/Multiple key value pair
}

I want to create a table by looping the object

$('#myTable thead tr').append('<th>Key Column</th>');
$('#myTable thead tr').append('<th>Value Column</th>');
var markup = '';
for (var i in obj) {
    markup = "<tr><td>" + i + "</td></td><td>" + obj[i] + "</td></tr>";
    $("#myTable tbody #first-col").append(markup);
}

But I am getting like this:

+-------------+--------------+
| Key Column  | Value Column |
+-------------+--------------+
| key1 value1 |              |
+-------------+--------------+
| key2 value2 |              |
+-------------+--------------+
| And so on.. |              |
+-------------+--------------+

Here is my HTML table

<table id="myTable">
   <thead>
      <tr>
      </tr>
   </thead>
   <tbody>
      <tr id="first-col">
      </tr>
   </tbody>
</table>

Kindly guide me how to perform it correctly. Or if it is better to generate the whole table again using jQuery, please let me know how to do it? Thanks

answered question

You are generating rows / <tr>s, but then instead of appending them to tbody, you're appending them to the first row...

To add on to Chris's comment, you also have one extra </td> after the key column.

"But I am getting like this" - You're looking at the wrong output. Don't only examine the final rendered result. Your code is building HTML. Look at the resulting HTML it builds. Does it look correct to you? Why not? What's wrong with it? If the resulting HTML string looks correct to you then you need some tutorials/guidance on how to create tables in HTML. If it doesn't look correct to you then it gives you all of the information you need to debug your code.

` $("#myTable tbody #first-col").append(markup);` your selector is not correct like @ChrisG said, use this $("#myTable tbody").append(markup);

as @dotoconnor said, markup = "<tr><td>" + i + "</td></td><td>" + obj[i] + "</td></tr>"; there is 1 extra closing tag </td>, u can use this <tr><td>" + i + "</td><td>" + obj[i] + "</td></tr>

1 Answer

0

Change this line:

$("#myTable tbody #first-col").append(markup);

To this:

$("#myTable tbody").append(markup);

Like so:

var obj = {
    key1: 'value1',
    key2: 'value2',
    key3: 'value3'
}

$(function() {  
  $('#myTable thead tr').append('<th>Key Column</th>');
  $('#myTable thead tr').append('<th>Value Column</th>');
  var markup = '';
  for (var i in obj) {
    markup = "<tr><td>" + i + "</td><td>" + obj[i] + "</td></tr>";
    $("#myTable tbody").append(markup);
  }
});

I also removed an extra </td> as mentioned in the comments.

Then it works. Codepen: https://codepen.io/haukurhaf/pen/jQWNGe

posted this

Have an answer?

JD

Please login first before posting an answer.