Home > Software engineering >  How to show a JSON value with numeric key in HTML table using AJAX
How to show a JSON value with numeric key in HTML table using AJAX

Time:03-17

I'm new to web development and I´ve been trying out building tables with data from different API´s but have run into a problem with a response that has numeric keys within the object.

I get the response to show in log but can not get the data to a table.

I reused the code from a previous test (that was successful), but in this test the keys are numeric. Here is the response:

{"345017":"Simo","345019":"Simola","345020":"email","360241":"This is a comment","360858":"CEO","360859":"Test Company AS","360895":"Mr.","362692":"Football"}

And here is the code that I've reused from the previous successful test:

window.onload=function(){


document.getElementById('button').addEventListener('click', loadRest);



  function loadRest() {
    window.onload=function(){
  document.getElementById('button').addEventListener('click', loadRest);
  
  function loadRest() {

var myArray =  []

buildTable(myArray)

$.ajax({
  method: 'GET',
  url: '(url here)',
  Accept: 'application/json',
  beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Bearer (token here)');
  },  
success:function(response){
    myArray = response
    buildTable(myArray)
    console.log(myArray)
  }
  })

function buildTable(object){
  var table = document.getElementById('myTable')


 {
for (var i = object; i < object.length; i  ){
    var row = `<tr>
            <td>${object[i][345017]}</td>
            <td>${object[i][345019]}</td>
            <td>${object[i][345020]}</td>
            <td>${object[i][360241]}</td>
            <td>${object[i][360858]}</td>
            <td>${object[i][360859]}</td>
            <td>${object[i][360895]}</td>
            <td>${object[i][362692]}</td>
          </tr>`
    table.innerHTML  = row

  
  }
}}}}

The differences between this and the successful one is that the successful one had letters as keys, for example <td>${items[I].name}</td> and that it was an array instead of an object.

Any help would be appreciated.

CodePudding user response:

you can try this code

function buildTable(obj){

var table = document.getElementById('myTable');

Object.keys(obj).forEach((prop) => {
var row = `<tr>
<td>${obj[prop]}</td>
 </tr>`
table.innerHTML  = row
});

}

result

Simo
Simola
email
This is a comment
CEO
Test Company AS
Mr.
Football
  • Related