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?

+3


source to share


4 answers


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



+5


source


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) %>

      

+1


source


[object Object]

comes from a function .toString()

. Example { a: 1 }.toString()

.

You need to encapsulate it in JSON.stringify(...)

for example: JSON.stringify({ a: 1 })

=> { "a": 1 }

.

0


source


For full printing Object

or Array

you can use:

JSON.stringify(obj, null, 4);

      

This returns the representation of the String

given object as a tree.

For example:

{a: 1, b: 2, c: {d: 4}}

      

becomes:

{
    "a": 1,
    "b": 2,
    "c": {
        "d": 4
    }
}

      

0


source







All Articles