user3187759 user3187759 - 3 months ago 8
Node.js Question

optimise efficiency in display mysql query results in node.js

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>

Answer

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>
Comments