简体   繁体   中英

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

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

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");} 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM