'How to display javascript variable values in a table
I'm currently in the process of creating a table that displays the variable values. I'm having trouble with implementing the values into my table. I have attached the code that I have so far. When I run this code I get "undefined" instead of the values. Any help would be appreciated.
<script>
var outputHTML = "";
var countries = {
"US": "Washington DC",
"UK": "London",
"Germany" : "Berlin",
"Estonia": "Tallinn",
"Morocco": "Rabat",
"Niger": "Niamey"
};
outputHTML += "<table border='2px' width='400'>";
for (var i =1; i <=6; i++) {
outputHTML += "<tr>";
for (var j =1; j <=2; j++) {
outputHTML += "<td>" + countries[i] + "</td>";
}
outputHTML +="</tr>";
}
outputHTML += "</table>";
document.getElementById("output").innerHTML = outputHTML;
</script>
Solution 1:[1]
use Object.keys(countries).forEach( key => // for loop here ) instead of for loop, and key will be prop name.
i.e. in the forEach loop countries[key] will get you the value, while key will get you the variable.
Solution 2:[2]
Use Object.entries(countries) to turn the object into a two dimensional array.
var outputHTML = "";
var countries = {
"US": "Washington DC",
"UK": "London",
"Germany" : "Berlin",
"Estonia": "Tallinn",
"Morocco": "Rabat",
"Niger": "Niamey"
};
outputHTML += "<table border='2px' width='400'>";
//REM: Returns the key/value of the object as array[[key, value]]
let tValues = Object.entries(countries);
//REM: Note - use .length instead of static 6 or foreach
//for (var i =1; i <=6; i++) {
tValues.forEach((item) => {
outputHTML += "<tr>";
//REM: We know item has two entries, so we can omit this loop.
//for(var j =0; j <=1; j++) {
// outputHTML += "<td>" + item[j] + "</td>";
//}
outputHTML += "<td>" + item[0] + "</td>";
outputHTML += "<td>" + item[1] + "</td>";
outputHTML +="</tr>";
})
outputHTML += "</table>";
document.getElementById("output").innerHTML = outputHTML;
<div id="output"></div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | big boy |
| Solution 2 |
