Home > Enterprise >  How to display javascript variable values in a table
How to display javascript variable values in a table

Time:03-04

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>

CodePudding user response:

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.

CodePudding user response:

Having countries as an object like you have shown is unusual and it might not be what you want.

Its more common to have array of objects like this

var countries = [
    {  
        country: 'US',
        city:  'Washington DC'
    },
    {  
        country: 'UK',
        city:  'London'
    },
    // etc
];

and then you would access them like this note that the first element of an array is 0

for (let i = 0; i < countries.length; i  ) {
        outputHTML  = '<tr><td>'   countries[i].country   '</td>'
                     <td>'   countries[i].city   '</td></tr>';
    }

CodePudding user response:

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>

  • Related