Steve Rodgers
Steve Rodgers

Reputation: 23

Looping through JSON and display each array item in HTML table

So, I was just about getting comfortable getting JSON data and displaying it in HTML when I ran in to the need to loop through items and display each keys and values. My objective is to display all 50 items in the JSON array and their information in a table. But whatever I try to do, the only output is nr 50. The last item in the array.

Here is my JSON:

{
"_embedded": {
    "enheter": [
        {
            "organisasjonsnummer": "995742594",
            "navn": "0-TAXI , KHAN TAIMUR",
            "organisasjonsform": {
                "kode": "ENK",
                "beskrivelse": "Enkeltpersonforetak",
                "_links": {
                    "self": {
                        "href": "https://data.brreg.no/enhetsregisteret/api/organisasjonsformer/ENK"
                    }
                }
            },
            "registreringsdatoEnhetsregisteret": "2010-07-15",
            "registrertIMvaregisteret": true,
            "naeringskode1": {
                "beskrivelse": "Drosjebiltransport",
                "kode": "49.320"
            },
            "antallAnsatte": 0,
            "forretningsadresse": {
                "land": "Norge",
                "landkode": "NO",
                "postnummer": "1473",
                "poststed": "LØRENSKOG",
                "adresse": [
                    "Kulturhusgata 1"
                ],
                "kommune": "LØRENSKOG",
                "kommunenummer": "0230"
            },
            "institusjonellSektorkode": {
                "kode": "8200",
                "beskrivelse": "Personlig næringsdrivende"
            },
            "registrertIForetaksregisteret": false,
            "registrertIStiftelsesregisteret": false,
            "registrertIFrivillighetsregisteret": false,
            "konkurs": false,
            "underAvvikling": false,
            "underTvangsavviklingEllerTvangsopplosning": false,
            "maalform": "Bokmål",
            "_links": {
                "self": {
                    "href": "https://data.brreg.no/enhetsregisteret/api/enheter/995742594"
                }
            }
        },//This is just the one item, the list goes on all the way up to 50.'

This is the code for extracting the data:

jQuery.ajax({
    url: 'https://data.brreg.no/enhetsregisteret/api/enheter?page=0&size=50&naeringskode=49.3,49.4,49.5&sort=navn.norwegian,asc',
    type: 'GET',
    data: {},
    dataType: 'json',
    success: (response) => {

      var listenhet = (response);
      var enhetArray = listenhet._embedded.enheter;

      for (var i = 0; i < enhetArray.length; i++) {
        console.log(enhetArray[i].navn);

        //Creating table
        var table ="<tr><td>"+enhetArray[i].forretningsadresse.kommune+"</td><td>"+enhetArray[i].navn+"</td><td>"+enhetArray[i].registrertIMvaregisteret+"</td><td>"+enhetArray[i].registreringsdatoEnhetsregisteret+"</td><td>"+enhetArray[i].naeringskode1.beskrivelse+"</td></tr>";
        

        //Showing the table inside tbody
        document.getElementById("myTB").innerHTML = table;   
      }
      console.log(response);
    },
    error: (response) => {
      console.log(response);
    } 
  })

Here is the table

<table class="table">
  <thead>
    <tr>
      <th scope="col">Sted</th>
      <th scope="col">Firmanavn</th>
      <th scope="col">MVA Registrert</th>
      <th scope="col">Reg Dato</th>
      <th scope="col">Beskrivelse</th>
    </tr>
  </thead>
  <tbody id="myTB">
  </tbody>
</table>

This is my output:

enter image description here

This is my console:

enter image description here

So, as you see, the console logs all 50 items. While my table only displays the last item in the array. How can I display all 50 items to the table so it becomes 50 table rows with the information I need about each item?

Upvotes: 0

Views: 3674

Answers (3)

Rajitha Alluri
Rajitha Alluri

Reputation: 117

You are creating a new variable 'var table' on each iteration which leads to erase the last contained data from the table variable and initialize with latest data. So that the data from the last iteration only exists in the table variable. Try creating a global variable outside of the loop

var table = "";

            for (var i = 0; i < enhetArray.length; i++) {
                console.log(enhetArray[i].navn);

                //Creating table
                var rowData ="<tr><td>"+enhetArray[i].forretningsadresse.kommune+"</td><td>"+enhetArray[i].navn+"</td><td>"+enhetArray[i].registrertIMvaregisteret+"</td><td>"+enhetArray[i].registreringsdatoEnhetsregisteret+"</td><td>"+enhetArray[i].naeringskode1.beskrivelse+"</td></tr>";

                // Store the value in 'table'
                table+= rowData;  
            }

And assign the 'table' variable to the 'myTB' from out side of the loop.

document.getElementById("myTB").innerHTML = table; 

Upvotes: 2

Anurag Srivastava
Anurag Srivastava

Reputation: 14413

You are creating this variable:

var table ="<tr><td>"+enhetArray[i].forretningsadresse.kommune+"</td><td>"+enhetArray[i].navn+"</td><td>"+enhetArray[i].registrertIMvaregisteret+"</td><td>"+enhetArray[i].registreringsdatoEnhetsregisteret+"</td><td>"+enhetArray[i].naeringskode1.beskrivelse+"</td></tr>";

And adding it to the innerHTML of #myTB

document.getElementById("myTB").innerHTML = table;   

But that means table has a new value in each iteration of the loop. So in the last iteration, whatever value is assigned to it, that is displayed in the table.

You need to store the value in a variable outside the loop like:

var total = ""; // Let this contain all the text
for (var i = 0; i < enhetArray.length; i++) {
    console.log(enhetArray[i].navn);

    //Creating table
    var table ="<tr><td>"+enhetArray[i].forretningsadresse.kommune+"</td><td>"+enhetArray[i].navn+"</td><td>"+enhetArray[i].registrertIMvaregisteret+"</td><td>"+enhetArray[i].registreringsdatoEnhetsregisteret+"</td><td>"+enhetArray[i].naeringskode1.beskrivelse+"</td></tr>";

    // Store the value in 'total'
    total+= table;  
}


// Set innerHTML to the combined value
document.getElementById("myTB").innerHTML = total;  

Upvotes: 1

Abhishek Raj
Abhishek Raj

Reputation: 490

just replace

    document.getElementById("myTB").innerHTML = table;   

with

    document.getElementById("myTB").innerHTML += table;   

Upvotes: 1

Related Questions