Send array value to Javascript, but it appears as [Object]
I am counting the number of results from the database and sending them as "TotalItems"
mysql_crawl.query('SELECT COUNT(*) FROM `catalogsearch_fulltext` WHERE MATCH(data_index) AGAINST("'+n+'") ', function(error, count) {
var r = count[0];
var totalItems = r,
res.render('result.html', {
totalItems: totalItems
})
});
I am trying to run console.log on r, the result is
RowDataPacket { 'COUNT(*)': 25 }
but when i run <% totalItems%> in javascript it shows as
[object Object]
How can I show an object as a number?
source to share
Specifying a template engine to render an object will cast the object to a string. This is done by looking at the object to see if it implements the method toString()
and if it will not traverse the object's prototype chain until it finds it.
In your example, the closest toString
is on the top level primitive Object
. This implementation just outputs [object Object]
. There is excellent information on this on MDN .
You can implement your own toString
and even wrap the object count
in a custom named and custom object toString
. But in your case, you have been given a generic object and I am (presumably) not at the level of code abstraction in more object oriented design patterns. In this case, the easiest way is to use your template code using JSON.stringify
, which will serialize any object to a string containing JSON data that is human readable for developers:
<% JSON.stringify(totalItems, null, 2) %>
source to share