0

The following line of code produces the title error:

  var tweets = <%= tweets %>;

In the chrome console it is displayed as the following:

var tweets = [object Object];

Why is this error being thrown? From similar questions it seems to be an issue of syntax but I am unsure how the above syntax can be changed?

I was initally stringifying the object before sending but this presented errors with unexpected characters being found.

user4357505
  • 135
  • 2
  • 9

1 Answers1

0

You get [object Object] when you convert an object to a string, which is what's happening with your templating system.

Example:

var obj = {
  stuff: 'things'
};
document.write(obj);

You can create a comparable object by printing out the JSON representation of that object:

var tweets = <%- JSON.stringify(tweets) %>;
//             ^-- Change to - instead of = to avoid escaping

This works because JSON is a subset of JavaScript and can therefore be used directly within JavaScript to create objects.

Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
  • Thanks for the response, stringifying the variable now raises the error I mentioned which is Uncaught SyntaxError: Unexpected token &, because the quotation marks are being represented as " – user4357505 May 17 '16 at 18:36
  • @user4357505 Then that all depends on what you're using to print it out. That's going to be responsible for how it handles printing text. – Mike Cluck May 17 '16 at 18:38
  • @Mike_C I'm unsure what you mean? the error is raised on the line that the variable is declared as you have stated in your answer – user4357505 May 17 '16 at 18:54
  • @user4357505 Whatever you're using to use that `<%= %>` syntax is formatting your data so it can be presented as HTML. To fix this problem, you need to change that so it produces the raw data. I don't know what you're using so I can't tell you how to fix that part. – Mike Cluck May 17 '16 at 19:13
  • Ah okay I see, I am using express routing to send the variable. 'res.render('index.html', {tweets: tweetobj};' Does it need to be handle before sending? – user4357505 May 17 '16 at 19:56
  • @user4357505 You could perform the `JSON.stringify(tweetobj)` before sending it. That is probably what you need. – Mike Cluck May 17 '16 at 19:58
  • @user4357505 Then it all depends on what template engine you're using. What template engine are you using to render your stuff from Express? – Mike Cluck May 17 '16 at 20:09
  • The engine is rendered with ejs, app.engine('html', require('ejs').renderFile); – user4357505 May 17 '16 at 20:11
  • @user4357505 Change `<%=` to `<%-`. Then the code [won't be escaped.](http://stackoverflow.com/questions/10326950/render-a-variable-as-html-in-ejs) – Mike Cluck May 17 '16 at 20:12