0

I have a query that returns an entire table. The only way I found to display the data as an HTML table is by creating an array for each column:

var date = [];
for (var i in arr) {
    date[i] = arr[i].nullinfoDate;
}
var number = [];
for (var i in arr) {
    number[i] = arr[i].nullinfoNumber;
}
var bool = [];
for (var i in arr) {
    bool[i] = arr[i].nullinfoBool;
}
var text1 = [];
for (var i in arr) {
    text1[i] = arr[i].nullinfoText1;
}
var text2 = [];
for (var i in arr) {
    text2[i] = arr[i].nullinfoText2;
}

and then sending all the columns to the HTML template:

app.get('/', function (req, res) {
    res.render('index', {
        title: 'home',
        date: date,
        number: number,
        bool: bool,
        text1: text1,
        text2: text2
    });
});

But that feels extremely inefficient. Is there a better way to do that?

HTML (EJS) template:

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <title><%= title %></title>
</head>
<body>
    <h1><%= title %></h1>
    <table>

    <% for(var i = 0; i < date.length; i++) {%>
    <tr>
        <td><%= date[i] %></td>
        <td><%= number[i] %></td>
        <td><%= bool[i] %></td>
        <td><%= text1[i] %></td>
        <td><%= text2[i] %></td>
    </tr>
    <% } %>

    </table>
</body>
</html>
3
  • Could you show your HTML template? Commented Aug 19, 2016 at 7:28
  • Thanks! Could you also describe how exactly the data returned by your query (arr) look like? Commented Aug 19, 2016 at 7:51
  • [ RowDataPacket { NULLINFOId: 7, nullinfoDate: Wed Aug 17 2016 13:48:18 GMT+0300 (IDT), nullinfoNumber: 877, nullinfoBool: 0, nullinfoText1: 'word', nullinfoText2: 'phrase' }, RowDataPacket { NULLINFOId: 8, nullinfoDate: Wed Aug 17 2016 13:48:53 GMT+0300 (IDT), nullinfoNumber: 924, nullinfoBool: 1, nullinfoText1: 'something', nullinfoText2: 'stuff' }, etc... Commented Aug 19, 2016 at 7:58

1 Answer 1

1

It seems it's enough to pass the data returned by your query directly:

app.get('/', function (req, res) {
    res.render('index', {
        title: 'home',
        data: arr
    });
});

Then in your template, you can just do:

<table>

<% for (let datum of data) {%>
<tr>
    <td><%= datum.nullinfoDate %></td>
    <td><%= datum.nullinfoNumber %></td>
    <td><%= datum.nullinfoBool %></td>
    <td><%= datum.nullinfoText1 %></td>
    <td><%= datum.nullinfoText2 %></td>
</tr>
<% } %>

</table>
Sign up to request clarification or add additional context in comments.

2 Comments

It worked! Thanks. Only with var or const instead of let, but no matter
@user3187759 Cool :)

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.