2

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);
    }
}
1
  • Images should not be used for textual data, such as a JS object or JSON data. Commented Apr 19, 2022 at 20:20

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

I knew it had to be something simple like that! Thank you so much!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.