Home > front end >  How to print an array from js to an ejs template?
How to print an array from js to an ejs template?

Time:12-23

I'm developing a kind of database-website where you can search people profiles.

I'm trying to print data from a database query but I get: [object Object].

Relevant code:

index.js

router.get('/profile/:name', function(req, res){

  db.query("SELECT name FROM people where name='Jack'",function(err,names){

    console.log(names);

    res.render('template', {person: names});
  });

  
});

template.ejs

<h1>Profile of <%= person %></h1>

With the console.log I'm getting what I expected:

[ RowDataPacket { name: 'Jack' } ]

How can I print only the name "Jack" in <=%person%>?

CodePudding user response:

The template can only display things like string and number that can directly be converted to a string with their .toString() method (since strings are what has to go into HTML). It can't directly display an object.

When you try to display an object, it calls .toString() on it and gets "[object Object]" so that's why you see what you see.

So, you need to add to your template exactly which properties of your object you want to display and how you want those different properties formatted in the HTML. Refer to the properties themselves in the template. I don't know exactly what form the data is that you're passing, but if it's an array, then you will have to refer to an array index or create an iterative loop in your template to display all the names in the array.

If you only want the first name from the array and the array is just a plain array of name strings (not an array of objects), you could change from this:

res.render('template', {person: names});

to this:

res.render('template', {person: names[0]});

And, that would then render that first name in the list with:

<h1>Profile of <%= person.name %></h1>
  • Related