Good day I need to write a table from a database and i can’t access the values, if the array is greater than 1… If i do it like this:
JavaScript
x
21
21
1
//spielzeiten
2
var spielzeitenArr = [{
3
spzeit: "",
4
spielzeit_id: "",
5
}];
6
var spzeitData = await myDB.selectSpielzeit();
7
8
for (var i = 0; i < 1/*spzeitData.length*/; i++) {
9
spielzeitenArr[i].spzeit = "meine Zeit" /*spzeitData.spzeit*/;
10
spielzeitenArr[i].spielzeit_id = "meine ID"/*spzeitData.spielzeit_id*/;
11
}
12
13
res.render('index', {
14
firmen: firmanameArr,
15
block: blocknameArr,
16
datei: dateinameArr,
17
jinglein: jingleinArr,
18
jingleout: jingleoutArr,
19
szdata: spielzeitenArr
20
});
21
and on the ejs side it looks like this:
JavaScript
1
20
20
1
<table id="todoTable">
2
<tr>
3
<td class="tdList">Datum</td>
4
<td class="tdList">Zeit</td>
5
<td class="tdList">Start Jingle</td>
6
<td class="tdList">End Jingle</td>
7
<td class="tdList">Name</td>
8
<td class="tdList">
9
<div class="select-wrapper">
10
<select id="categoryFilter" class="selectCompany"></select>
11
</div>
12
</td>
13
14
<% szdata.forEach((item) => { %>
15
<tr></tr>
16
<td><%= item.spzeit %></td>
17
<td><%= item.spielzeit_id %></td>
18
<% }); %>
19
</table>
20
if i use my hardcoded value, it works. But if i try to change the i value to 2 or more, it gives me an error… why is this so?
Many thanks for the help!
Advertisement
Answer
You are initializing your spielzeiten
array with a length of 1 and not increasing its size if you have more than one record. Thus, of course if you try to access an spielzeiten[i].spzeit
with an index different from 0 you get an error.
You should probably initialize your array as an empty array and add new items during the loop.
JavaScript
1
9
1
spielzeiten = [];
2
3
for (let i = 0; i < spzeitData.length; i++) {
4
spielzeiten.push({
5
spzeit: spzeitData[i].spzeit,
6
id: spzeitData[i].spielzeit_id
7
});
8
}
9
You could also use the Array.map
function to directly initialize your array
JavaScript
1
5
1
let spielzeiten = spzeitData.map(d => ({
2
spzeit: d.spzeit,
3
id: d.spielzeit_id
4
}));
5