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:
//spielzeiten var spielzeitenArr = [{ spzeit: "", spielzeit_id: "", }]; var spzeitData = await myDB.selectSpielzeit(); for (var i = 0; i < 1/*spzeitData.length*/; i++) { spielzeitenArr[i].spzeit = "meine Zeit" /*spzeitData.spzeit*/; spielzeitenArr[i].spielzeit_id = "meine ID"/*spzeitData.spielzeit_id*/; } res.render('index', { firmen: firmanameArr, block: blocknameArr, datei: dateinameArr, jinglein: jingleinArr, jingleout: jingleoutArr, szdata: spielzeitenArr });
and on the ejs side it looks like this:
<table id="todoTable"> <tr> <td class="tdList">Datum</td> <td class="tdList">Zeit</td> <td class="tdList">Start Jingle</td> <td class="tdList">End Jingle</td> <td class="tdList">Name</td> <td class="tdList"> <div class="select-wrapper"> <select id="categoryFilter" class="selectCompany"></select> </div> </td> <% szdata.forEach((item) => { %> <tr></tr> <td><%= item.spzeit %></td> <td><%= item.spielzeit_id %></td> <% }); %> </table>
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.
spielzeiten = []; for (let i = 0; i < spzeitData.length; i++) { spielzeiten.push({ spzeit: spzeitData[i].spzeit, id: spzeitData[i].spielzeit_id }); }
You could also use the Array.map
function to directly initialize your array
let spielzeiten = spzeitData.map(d => ({ spzeit: d.spzeit, id: d.spielzeit_id }));