I would like to insert parsed JSON data into a HTML table via Javascript. I think I am close to a solution, but can't figure out the final step.
Goal: I need to insert the name, age, secretIdentity and powers of three superheroes into their respective columns in a table. The data comes from a JSON file. I parsed it and it is ready to use in Javascript. I want to loop through the objects within the data and insert the correct data in the cells. I am not allowed to use jQuery or similar techniques.
Problem: The problem is that I can not seem to loop through the objects (name, age etc) for each superhero and add it to the cell. How do I target/reference the objects for use in a loop? For example, this 'works', but gives the wrong result since I don't want to loop through the names:
JavaScript code:
for(i = 0; i < members.length; i++) {
function addRow(tableID) {
let tableRef = document.getElementById(tableID);
let newRow = tableRef.insertRow(-1);
for(x = 0; x < 4; x++) {
let newCell = newRow.insertCell(0);
let newText = document.createTextNode(members[i].name);
newCell.appendChild(newText);
}
Instead, I want to loop through the object like this, in a horizontal way.
Expected solution: I expect the solution to look something like this, but it doesn't work:
for(x = 0; x < 4; x++) {
let newCell = newRow.insertCell(0);
let newText = document.createTextNode(members[i].obj[x]);
newCell.appendChild(newText);
JSON data:
const data =
[ { squadName : 'Super Hero Squad'
, homeTown : 'Metro City'
, formed : 2016
, secretBase : 'Super tower'
, active : true
, members :
[ { name : 'Molecule Man'
, age : 29
, secretIdentity : 'Dan Jukes'
, powers :
[ 'Radiation resistance'
, 'Turning tiny'
, 'Radiation blast'
] }
, { name : 'Madame Uppercut'
, age : 39
, secretIdentity : 'Jane Wilson'
, powers :
[ 'Million tonne punch'
, 'Damage resistance'
, 'Superhuman reflexes'
] } ] }
//, {}
]
Is there anyone that is able to help out? Thanks in advance!