Get data from API via $.get() function and use append method to add rows to tbody tag.
For example;
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<table>
<thead>
<tr>
<th>Course</th>
<th>Level</th>
<th>Provider</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script src="app.js"></script>
</body>
</html>
app.js:
function createTable(data){
const {course, level, provider} = data;
const tableBody = $('tbody');
for (let i; i<provider.length; i++){
const school = provider[i].school;
tableBody.append(`
<tr>
<th>${course}</th>
<td>${level}</td>
<td>${school}</td>
</tr>
`)
}
}
$.get('<url>', createTable);
[
{
"course": "Bachelor of Computer Science",
"level": "Bachelor's Degree",
"provider": [
{
"school": "Harvard University",
"duration": "156"
},
{
"school": "Yales University",
"duration": "156"
},
{
"school": "BYU-Provo",
"duration": "208"
}
]
}
]
I am fetching data from an API and it gives me something like the above code. I want to create a table. I did something like this
data .map((item) => {
return `
<tr class="grid-row">
<td>${item.course}</td>
<td>${item.level}</td>
${provider(item.provider)} // Loops through the provider array
</tr>
and I get something like this
Course |
Level |
Provider |
Science |
BSC. |
Harvard University Yales University BYU-PROVO |
How to create a new row with a different provider but the same course and level? So that it would create something like this
Course |
Level |
Provider |
Science |
BSC. |
Harvard University |
Science |
BSC. |
Yales University |
Science |
BSC. |
BYU-Provo |
|
|
|
{course, level, provider} = data if I console.log (course) it says undefined. I am getting the data though.
I realise your main data is array, right now. Your should edit code section of your question. So you need get object from array by index. Try something like that const {course, level, provider} = data[0];
I did [{course,level,provider}] = data and it worked. Thanks for your help. It did work.