-2

I am trying to insert my array data into a table that I have created. This is my code to put the data into arrays:

    const theAccounts = GetAccountsArray();
    console.log(theAccounts);

    const theIds = [];
    const theNames = [];

    for(var theAccount in theAccounts)
    {
             theNames.push(theAccounts[theAccount]["Name"]);
             theIds.push(theAccounts[theAccount]["Id"]);
    }

This is my table:

<tr>
  <th>Account Id</th>
    <th>Account Name</th>
    </tr>

    <tr>
    <td> theIds </td>
    <td> theNames </td>
    </tr>
    </table>
    </td>

TheNames and TheIds represent where I want the data to be.

This is what I did to display the table using @Bizoon 's suggestion:

<table id ="theTable" style="width: 100%; border: 1px solid black; ">
</table>

var theTable = "";
    theTable +="<tr>";
    theTable += "<th style='border: 1px solid black'>Account Id</th>";
    theTable += "<th style='border: 1px solid black'>Account Name</th>";
    theTable += "</tr>";
  for (var i in theAccounts)
    {
        theTable += "<tr>";
    theTable += "<td style='border: 1px solid black'>" +
    theAccounts[i]["Id"] + "</td>" +
    "<td style='border: 1px solid black'>" + theAccounts[i]["Name"] + "</td>";
    theTable += "</tr>";
    document.getElementById("theTable").innerHTML = theTable;
    }

Do let me know if there is a better way to do this.

mmm
  • 69
  • 8
  • Does this answer your question? [Generate HTML table from 2D JavaScript array](https://stackoverflow.com/questions/15164655/generate-html-table-from-2d-javascript-array) – Justinas Apr 21 '21 at 08:28
  • My aim is to just populate the table with the 2 arrays that I made. I already made the table head. – mmm Apr 21 '21 at 08:53
  • Ok, so do it. Or is there any issues with that? – Justinas Apr 21 '21 at 08:53
  • I am not that sure about how to exactly do that as most of the suggestions involve creating the table from the array itself and not inserting the array data to the html. – mmm Apr 21 '21 at 08:58
  • That's the way to go with dynamically creating elements. Unless you use some JS Framework, like Angular or React – Justinas Apr 21 '21 at 09:38

1 Answers1

0

Maybe something like that

function populate() {
    var table = "";
    for (var i in data) {
        table += "<td>" +
        data[i].name + "</td>" +
        "<td>" + data[i].id + "</td>";
        table += "</tr>";
        document.getElementById("#selectdiv").innerHTML = table;
    }
}
Ajith Gopi
  • 1,509
  • 1
  • 12
  • 20
Bizoon
  • 51
  • 2