简体   繁体   中英

Javascript: How to iterate through an array of values and create table rows

I am fetching data from a server, I would like to iterate through the values and display them into the first column of the table. Any help that can steer me in the right direction would be appreciated.

Javascript

fetch(_____,{
}).then(data => {
    var mstone = data.MilName;

    var table = document.getElementById("milestone-table");
    var row = table.insertRow(table.rows.length);
    // var cell1 = row.insertCell(0);
    //var cell2 = row.insertCell(1);

    //cell1.setAttribute("style", "text-align:center");
    //cell2.setAttribute("style", "text-align:center");
    
    //Iterating through data values and trying to display onto table
    for(var i = 0; i < mstone.length; i++){
        var cell = row.insertCell(0);
        cell.setAttribute("style", "text-align:center");
        cell.innerHTML = mstone[i]; 
    }

}).catch(function(err){
    console.log("Fetch Problem: " + err);
});

You can set up the table in HTML without any of rows added, loop through the response data and add a row and cell for each item.

 const data = ['foo', 'bar', 'baz'] // Dummy response data const tbody = document.querySelector('tbody'); data.forEach(item => { const tr = tbody.insertRow(); tr.insertCell().innerText = item })
 <table> <thead> <tr> <th>Column Heading</th> </tr> </thead> <tbody> </tbody> </table>

Try some thing like below. Have nested loops (1 for rows and 1 for columns)

 fetch("https://swapi.dev/api/planets/").then((res) => res.json()).then((resp) => { const results = resp.results; var table = document.getElementById("table"); for (let j = 0; j < 4; j++) { var row = table.insertRow(j); for (var i = 0; i < 4; i++) { var cell = row.insertCell(0); cell.setAttribute("style", "text-align:center; border: 1px solid blue;"); cell.innerHTML = Object.values(results[j])[i]; } } });
 <table id="table" style="border: 1px solid grey"></table>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM