Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send array value on Javascript but it show as [object Object]

I count number of result from database and send 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 try running console.log on r, result is

RowDataPacket { 'COUNT(*)': 25 }

but when I run <% totalItems %> on javascript, it show as

[object Object]

How can I show object as number?

like image 397
Moomoo Soso Avatar asked Jul 25 '26 16:07

Moomoo Soso


2 Answers

totalItems is object, you can access its values by totalItems['COUNT(*)']

like image 66
Luke Avatar answered Jul 27 '26 07:07

Luke


Telling a template engine to render an object will cast the object into a string. This is done by looking at the object to see if it implements a toString() method and if not will walk the object's prototype chain till it finds one.

In you example the closest toString is on the top level primitive Object. This implementation simply outputs [object Object]. There is excellent information about this is on MDN.

You could implement your own toString and even wrap the count object in a custom object with a name and custom toString. But in your case you were given a generic object and am (presumably) not at the level of abstracting code in more object oriented design patterns. In this case it is simply easier to wrap your template code use with JSON.stringify which will serialize any object into a string containing JSON data which is human readable for developers:

<% JSON.stringify(totalItems, null, 2) %>
like image 41
Sukima Avatar answered Jul 27 '26 07:07

Sukima