Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passing an array into an HTML table or variable

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
    }
}

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading