3

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?

1

4 Answers 4

5

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

[object Object] comes from the .toString() function. Example: { a: 1 }.toString().

You need to encapsulate it in JSON.stringify(...), example: JSON.stringify({ a: 1 }) => { "a": 1 }.

Comments

0

For full printing of an Object or Array, you can use:

JSON.stringify(obj, null, 4);

This returns a String representation of the given Object as a tree.

For example:

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

becomes:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.