Mousa Saleh
Mousa Saleh

Reputation: 38

Making table using for-loop

I have this code. It's very good and has no error in it. But I don't like repeat the code html += "td"; a lot. Eaven html += "/td";. It is seing not clearly code. How can I code it in shorter code using for loop?

html = "<table>";
html += "<tr>";
for(var name in newArticle[1]){
  html += "<th>";
  html += name;
  html += "</th>";
}
html += "</tr>";
for (var i=0; i<newArticle.length; i++) {
    html += "<tr>";
    html += "<td>";
    html += newArticle[i]["id"];
    html += "</td>";
    html += "<td>";
    html += newArticle[i]["Forename"];
    html += "</td>";
    html += "<td>";
    html += newArticle[i]["Surname"];
    html += "</td>";
    html += "<td>";
    html += newArticle[i]["Age"];
    html += "</td>";
    html += "<td>";
    html += newArticle[i]["City"];
    html += "</td>";
    html += "<td>";
    html += newArticle[i]["ZIP"];
    html += "</td>";
    html += "</tr>";
}
html += "</table>";
  console.log(html);

  for(var name in newArticle[1]){
    console.log(name);
  }

You can note that newArticle() is an array and the table data is from array's elements.

Upvotes: 0

Views: 194

Answers (2)

Murad Sofiyev
Murad Sofiyev

Reputation: 791

newArticle = 
html = "<table>";
html += "<tr>";
for(var name in newArticle[1]){
  html += "<th>";
  html += name;
  html += "</th>";
}
html += "</tr>";
for (var i=0; i<newArticle.length; i++) {
  html += "<tr>";
  for(var key in newArticle[i])
  {
    html += "<td>";
    html += newArticle[i][key];
    html += "</td>";
  }
  html += "</tr>";
}
html += "</table>";
console.log(html);    
for(var name in newArticle[1]){
  console.log(name);
}

Upvotes: 1

Viraj Prateek
Viraj Prateek

Reputation: 5

Define a new array (say myarr with elements in order as required by the column of the newArticle array. Now to use the newArticle array in for loop like this -

newArticle[i][myarr[j]] ;

You can initiate j from 0 and keep incrementing it to get the next respective values . Hope it helps .

Upvotes: 0

Related Questions