Home > database >  Passing an array into an HTML table or variable
Passing an array into an HTML table or variable

Time:04-18

I am trying to pass information from an API call into an HTML table which I can then also use for graphs. A picture of the array is attached to show the data structure. I keep receiving an error that column_names is not iterable but I have not been able to work it out after hours of searching. I think it has to do with the names in my array but can't find a solution. I'm new to this and I feel like the answer is painfully simple so any help or explanation of my error would be appreciated.

Array Format

enter image description here

async function loadintotable(url, table) {
    const tableHead = table.querySelector('thead');
    const tableBody = table.querySelector('tbody');
    const response = await fetch(url);
    const { column_names, data } = await response.json();

    tableHead.innerHTML = '<tr></tr>';
    tableBody.innerHTML = '';
    for (const headerText of column_names) {
        const headerElement = document.createElement('th');

        headerElement.textContent = headerText;
        tableHead.querySelector('tr').appendChild(headerElement);
    }

    for (const row of data) {
        const rowElement = document.createElement('tr');

        for (const cellText of row) {
            const cellElement = document.createElement('td');

            cellElement.textContent = cellText;
            rowElement.appendChild(cellElement);
        }

        tableBody.appendChild(rowElement);
    }
}

CodePudding user response:

Your api response is of format

{
  dataset: {
    column_names: [],
    data: []
  }
}

So, in order to access column_names and data you have to

const json = await response.json();
const { column_names, data } = json.dataset;

Or in one line

const { column_names, data } = (await response.json()).dataset;

Notice the .dataset at the end of the line

  • Related