0

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.

2
  • 1
    No, it's not very good. newArticle() is not an array, it's a function call. But there's no function like that, it's undefined, which would make this whole thing to have at least one error. Your indentation is off, you don't properly declare variables and it's just bad, bad, bad. Welcome to StackOverflow. Commented Jun 11, 2017 at 19:37
  • 3
    Don't manually create HTML like that. Look up the createElement and similar functions. Create element objects and append children to them. Commented Jun 11, 2017 at 19:40

2 Answers 2

1
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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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 .

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.