Skip to content

Javascript i need to show data in table from dynamic object keys

Hello everyone I have a array of objects now those objects hold have multiple keys and those keys are dynamic so I have no idea how can I loop through data and show them in the table I am not sure how can I access those when I loop through. I was able to get the object keys into a separate array but don’t how to utilize them. Here is the array of data and the array of keys can anyone guide or help me

This is the data array

var data = {
"data": [
        {
            "nationality": "Indonesia",
            "gender": "Male",
            "country": "Indonesia",
            "preferred_role": "Customer Service",
            "work_experience": "More than 1 year and less than 2 years",
            "preferred_work_environment": "Open to both",
            "count": 381
        },
              ]
    }

This is the keys array

["nationality", "gender","country","preferred_role","work_experience","count","preferred_work_environment"]

Answer

We can access those keys dynamically via Object.keys() and then perform iteration.

Working Demo :

const arr = [{
  "nationality": "Indonesia",
  "gender": "Male",
  "country": "Indonesia",
  "preferred_role": "Customer Service",
  "work_experience": "More than 1 year and less than 2 years",
  "preferred_work_environment": "Open to both",
  "count": 381
}, {
  "nationality": "USA",
  "gender": "Female",
  "country": "US",
  "preferred_role": "Customer Service",
  "work_experience": "More than 2 years and less than 5 years",
  "preferred_work_environment": "Open to both",
  "count": 382
}];

function tableCreate () {
  var myTable = document.getElementById('myDynamicTable');
  var table = document.createElement('table');
  table.border = '1';
  var tblBody = document.createElement('tbody');
  
  for(var i = 0; i < arr.length; i++){
    var tr = document.createElement('tr');
    tblBody.appendChild(tr)
    for(var j=0; j< Object.keys(arr[i]).length; j++) {
        var td = document.createElement('td');
      td.innerHTML = arr[i][Object.keys(arr[i])[j]];
      tr.appendChild(td);
    }
  }
  
  table.appendChild(tblBody);
  myTable.appendChild(table);
}

tableCreate();
@font-face{
  font-family:'Bitstream Vera Serif Bold',
  src:url('https://mdn.mozillademos.org/files/2468/VeraSeBd.ttf')
}
body{
font-size:90%;
}
table{
  font-family: Arial, serif;
  border-collapse:collapse;
}
table tr, table td{
  border:1px solid #ccc;
  padding: 8px;
}
<div id="myDynamicTable">
</div>