user1584421
user1584421

Reputation: 3863

Node.js Object on the server is not an object on the client

I have a variable on the server side of Node.js that is an object. I can verify this with console.log(typeof(value)); and i get object.

When I do a console.log(value); I get

[ 'bla_bla_1',
  'bla_bla_2',
  'bla_bla_3',
]

Then I pass the variable to the client with Express: res.render('target.ejs', {data:value}); and the ejs file parses it with var value = '<%= data %>';

I want to know if it is an object or an array, in order to figure out how to handle it on the client side.

I wrote a little script to test it:

if (typeof(value) === 'object') {console.log("IT'S AN OBJECT");}
else {console.log("IT'S NOT AN OBJECT");}
if ( Array.isArray(value) ) {console.log("IT'S AN ARRAY");}
else {console.log("IT'S NOT AN ARRAY");}

What I get back is this in the console of the browser:

IT'S NOT AN OBJECT
IT'S NOT AN ARRAY

Upvotes: 0

Views: 195

Answers (3)

zmag
zmag

Reputation: 8251

The value is a simple string after getting parsed with EJS syntax.

EJS Doc specifies how to set a value as it is.

<%- Outputs the unescaped value into the template

Try below:

var value = <%- JSON.stringify(data) %>;

Upvotes: 2

Ernesto
Ernesto

Reputation: 4272

Objects have “{“ and “}” const obj = { Key2: “value” }

And arrays have [ ]

Objects have key value, arrays don’t, but if you are an orthodox person then you’ll know that at the of the day and array is an object

Do not trust me on this but I think typeof is used on primitive values, and as we know arrays an objects are not, there for is better to use instanceof

Upvotes: 2

gaetanoM
gaetanoM

Reputation: 42054

From MDN:

Property names must be double-quoted strings; trailing commas are forbidden.

That means you need to replace invalid chars before parsing:

var origvalue = "[ 'bla_bla_1','bla_bla_2','bla_bla_3', ]";
var value =  JSON.parse(origvalue.replace(/'/g, '"').replace(/,[^,]*\]/, '\]'));
if (typeof(value) === 'object') {console.log("IT'S AN OBJECT");}
else {console.log("IT'S NOT AN OBJECT");}
if ( Array.isArray(value) ) {console.log("IT'S AN ARRAY");}
else {console.log("IT'S NOT AN ARRAY");}

Upvotes: 2

Related Questions