user644745
user644745

Reputation: 5713

passing locals array from Express to Javascript

I am using Jade and

- if (userId !== null)
  != "<script type='text/javascript'>"
  != "userDetail.userId = "+userId.toString()+";"
  - if (friends && friends.length > 0)
    != "userDetail.friends = "+friends+";"
  != "</script>"

In Javascript, userDetail.js,

var userDetail = {};

userDetail.userId = null;
userDetail.friends = [];

When I run this I get - Uncaught SyntaxError: Unexpected token ILLEGAL

I am able to refer to userDetail.userId in JS, but userDetail.friends appears as null. Any clue what's wrong ?

friends is an array of object {id, name, _id}

Upvotes: 0

Views: 864

Answers (1)

Peter Lyons
Peter Lyons

Reputation: 146054

You need to use JSON.stringify(friends) as opposed to the default friends.toString() that you have.

node
> [{id: 42, name: "ray"}].toString()
'[object Object]'
> JSON.stringify([{id: 42, name: "ray"}])
'[{"id":42,"name":"ray"}]'

Upvotes: 4

Related Questions