I have this script that gets the csv file, and separates it by column. I am having trouble to display the values in a table. I can’t seem to get each column to create a new table row. Any help will be appreciated as I am not very good at JS.
JavaScript
x
21
21
1
<script>
2
getData();
3
4
async function getData() {
5
const response = await fetch('data.csv')
6
const data = await response.text();
7
console.log(data);
8
9
10
const table = data.split('n');
11
table.forEach(row => {
12
const columns = row.split(',')
13
const date = columns[0]
14
const temp = columns[1]
15
16
console.log(date, temp);
17
})
18
19
}
20
</script>
21
The data.csv looks something like this:
JavaScript
1
9
1
17-10-2020,25
2
17-10-2020,25
3
17-10-2020,25
4
17-10-2020,25
5
17-10-2020,25
6
17-10-2020,25
7
17-10-2020,25
8
17-10-2020,25
9
The console.log(data, temp) returns without the commas. My only problem is trying to get them inside a table using Javascript.
JavaScript
1
13
13
1
<table class="table text-left mt-2" id="data">
2
<thead class="thead-dark">
3
<tr>
4
<th scope="col">#</th>
5
<th scope="col">Date/Time</th>
6
<th scope="col">Temperature</th>
7
</tr>
8
</thead>
9
<tbody>
10
<!-- Generate the csv table rows here -->
11
</tbody>
12
</table>
13
Advertisement
Answer
JavaScript
1
28
28
1
const tableBody = document.getElementById("table-body");
2
3
4
5
getData();
6
7
async function getData() {
8
const response = await fetch('data.csv')
9
const data = await response.text();
10
console.log(data);
11
12
13
const table = data.split('n');
14
table.forEach((row,index) => {
15
const columns = row.split(',')
16
const date = columns[0]
17
const temp = columns[1]
18
console.log(date, temp);
19
const tr = document.createElement("tr");
20
tr.innerHTML = `
21
<td>${index + 1}</td>
22
<td>${date}</td>
23
<td>${temp}</td>
24
`;
25
// finally add the <tr> to the <tbody>
26
tableBody.append(tr);
27
})
28
}
JavaScript
1
12
12
1
<table class="table text-left mt-2" id="data">
2
<thead class="thead-dark">
3
<tr>
4
<th scope="col">#</th>
5
<th scope="col">Date/Time</th>
6
<th scope="col">Temperature</th>
7
</tr>
8
</thead>
9
<tbody id='table-body'>
10
<!-- Generate the csv table rows here -->
11
</tbody>
12
</table>
Try this and let me know if its working or not. Please note i’ve added an ID to the table body and selecting that via ID.