Question: How can I retrieve the properties of a data object in EJS/node.js?

Question

How can I retrieve the properties of a data object in EJS/node.js?

Answers 2
Added at 2017-01-04 16:01
Tags
Question

I am passing a data object, as a parameter, to the render method, and assigning to it the variable name "values".

app.get('/', function(req, res) {
  var query = 'SELECT AVG(numUsers) FROM attendance';
  connection.query(query, function(err, results) {
    if(err) {
      console.log(err);
    }
    console.log(results);

    for(var i = 0; i < results.length; i++) {
      var values = results[i];
    }

    res.render('index', { values: results });
  });
});

The console prints the following results object value:

[ RowDataPacket { 'AVG(numUsers)': 13.75 } ]

In my EJS template file, I reference this object to retrieve its property values:

<table>
  <tr>
    <th>Average attendance</th>
  <tr>
  <% for(var i = 0; i < values.length; i++) { %>
    <tr>
      <td><%- JSON.stringify(values) %></td>
    </tr>
  <% } %>
</table>

On my index page, the following string is printed:

[{"AVG(numUsers)":13.75}]

How can I retrieve the isolated integer value, 13.75, directly from the data object?

Answers
nr: #1 dodano: 2017-01-04 16:01

I would rather try to stringify the "values" variable before passing it to the View from the Controller. Then iterate and make an array of values and then send it to the View.

If you do a console log of your object (results[i]) from the Controller, you should be able to see an object containing an array of AVG(numUsers) in the console, with that you can make your own array of results and then pass it to the View and iterate it with a foreach properly.

Hope it helps!

nr: #2 dodano: 2017-01-04 16:01

According to your console output results is an array out of objects. This means for accessing the first found match in the database you would access it like console.log(results[0]);

As you don't want to access the entire result object but only the value of its index AVG(numUsers) you can print it like console.log(results[0]['AVG(numUsers)']);

So your loop in the router needs to look like:

var values = [];
for(var i = 0; i < results.length; i++) {
    values[i] = results[i]['AVG(numUsers)'];
}
res.render('index', { values: values });

if you want to have a clean array, only including the float values.

And in your template file simply:

<% for(var i = 0; i < values.length; i++) { %>
   <tr>
     <td><%- values[i] %></td>
   </tr>
<% } %>
Source Show
◀ Wstecz