How to access node JS array in javascript?

In my Node JS application I’m returning response to index html page like this

res.render('index', {items:masterArray});

in index html page, I just want to give a alert for items[1] using javascript.

how to do this in javascript ?

alert(items[1]) // does not work

what is the correct syntax ?

What is items[1]? String? Number? Array? Boolean? Object? Do you get any error messages?

Its Array.

Error is , “items is not defined”

Let me rephrase the question again,

In Node JS, I have this

res.render('index', {items:masterArray});

in index html page I access the items like this

<script>
  alert(items[1]);
 </script>

Can I access this way ? if not what is the right syntax ?

Is this supposed to be the array?
{items:masterArray}

What is the value of masterArray ?

masterArr holds 3 populated arrays. Code below

In Node Express JS I have ,

var masterArry=[];
var strikeArr=[];
var callArr=[];
var putArr=[];
//strikeArr populated
//callArr populated
//putArr populated

masterArry.push(strikeArr);
masterArry.push(callArr);
masterArry.push(putArr);
res.render('index', {items:masterArray});

In index html page, this is not working

<script>
  alert(items[1]); //I expect this to print callArr
</script>

Error : items is not defined.

What is the right syntax here ?

Sure you can pass a variable to your template. How you do so depends upon the templating engine you are using.

Here’s how you’d do it using pug:

app.js

const express = require('express');
const app = express();
const port = 3000;

app.set('view engine', 'pug');
app.get('/', (req, res) => {
  res.render('index', { items: [1, 2, 3] });
});

app.listen(port, () => console.log(`Example app listening on port ${pot}!`));

index.pug

html
  head
  body
    script alert("#{items}")

I want to access this in javascript in index html page. Is it possible ?
I dont want template.

Nope. I don’t think you can do this with Node and HTML alone. It’s not like using PHP, where you can echo stuff to the page without any further setup necessary.

okay. fine. if its not doable by javascript , let me try with template then.

I’m already using handlebar template in index.hbs page

Here is a bad handlebar code . I am not sure how to fix this but this is what I need.

{{# each items }}
		<div>
		<script>
		var strikeData="{{this[0]}}"
		var callData="{{this[1]}}"
		var putData="{{this[2]}}"
		
		// I can now invoke highcharts charting libary and pass these JS data arrays to chart.
		</script>
		
	    </div>
	    {{/each}}

It should be possible. Are you using express-handlebars? If not, could you provide some more info so I can understand your setup.

yes…you are right.

here is my view set up

var hbs = require('express-handlebars');

var routes = require('./routes/index');

var app = express();

// view engine setup
app.engine('hbs', hbs({extname: 'hbs', defaultLayout: 'layout', layoutsDir: __dirname + '/views/layouts/'}));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

You can just do this in index.hbs:

<script>
  const items=[{{items}}];
  const strikeData = items[0];
  const callData = items[1];
  const putData = items[2];
</script>

No need to iterate over the array using Handlebars. Just assign it to a variable and work with that instead.

Or slightly neater:

<script>
  const [strikeData, callData, putData] = [{{items}}];
</script>

are you sure ?

I’m still getting error “items is not defined

here is the code

<script>
  const items=[{{items}}];
  const strikeData = items[0];
  const callData = items[1];
  const putData = items[2];
  alert(strikeData);
  alert(callData);
  alert(putData);
</script>

Yup.

Try a minimal example to isolate the problem:

package.json

{
  "name": "my-proj",
  "version": "1.0.0",
  "description": "whatever",
  "dependencies": {
    "express": "^4.16.4",
    "express-handlebars": "^3.0.0",
  }
}

server.js

const path = require('path');
const express = require('express');
const hbs  = require('express-handlebars');
const app = express();
const port = 3000;

app.engine('hbs', hbs({ extname: 'hbs', defaultLayout: 'layout', layoutsDir: __dirname + '/views/layouts/'}));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

app.get('/', (req, res) => {
  res.render('index', { items: [1, 2, 3] });
});

app.listen(port, () => console.log(`Example app listening on port ${port}!`));

views/layouts/layou.hbs

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Example App</title>
</head>
<body>
  {{{body}}}
</body>
</html>

views/index.hbs

<h1>Example App</h1>

<script>
  const [strikeData, callData, putData] = [{{items}}];
  alert(strikeData);
  alert(callData);
  alert(putData);
</script>

Folder structure:

.
├── package.json
├── package-lock.json
├── server.js
└── views
    ├── index.hbs
    └── layouts
        └── layout.hbs

Also, be aware that my example uses ES6 which wouldn’t be supported by ancient browsers (e.g. IE).

If you run the above, then visit http://localhost:3000, you should see the values of items alerted to the page one after another.

1 Like

will check this out and revert back
thanks

Is there anything wrong in this code. Its not rendering !

in Express JS code

var masterArry = [];
var strikeArr = [];
var callArr = [];
var putArr = [];
for (i = 0; i < openinterestdocs.length; i++) {

  var jsonData = openinterestdocs[i];

  var rowList = jsonData.rows;

  for (j = 0; j < rowList.length; j++) {
    //console.log(rowList[j].c[0].v);
    strikeArr.push(rowList[j].c[0].v);
    //console.log(rowList[j].c[1].v);
    callArr.push(rowList[j].c[1].v);
    //console.log(rowList[j].c[2].v);
    putArr.push(rowList[j].c[2].v);
  }

  masterArry[i].push(strikeArr);
  masterArry[i].push(callArr);
  masterArry[i].push(putArr);
  console.log(masterArry); // This prints okay.								
}

res.render('index', {
  openinterest: masterArry
});

In Handlebar index.hbs

<script>
   
  const openinterest = [{
   {
     openinterest
   }
 }];

 var arrayLength = openinterest.length;

 for (var i = 0; i < arrayLength; i++) {
   alert(openinterest[i][0]);
   alert(openinterest[i][1]);
   alert(openinterest[i][2]);
</script>

I’m not getting any alert.

What does this log to the console?

<script>console.log({{openinterest}});</script>

And,

What does it print?

I made some changes to code and deployed.

this is current server code and this is the log in server console.

console.log("************FEST*******************");
console.log("openinterestdocs" + openinterestdocs);
console.log("openinterestdocs.length =" + openinterestdocs.length);
var masterArry = [];
var strikeArr = [];
var callArr = [];
var putArr = [];
for (i = 0; i < openinterestdocs.length; i++) {

  var jsonData = openinterestdocs[i];

  var rowList = jsonData.rows;

  for (j = 0; j < rowList.length; j++) {
    //console.log(rowList[j].c[0].v);
    strikeArr.push(rowList[j].c[0].v);
    //console.log(rowList[j].c[1].v);
    callArr.push(rowList[j].c[1].v);
    //console.log(rowList[j].c[2].v);
    putArr.push(rowList[j].c[2].v);
  }

  masterArry[i].push(strikeArr);
  masterArry[i].push(callArr);
  masterArry[i].push(putArr);
  console.log(masterArry); // Log  not printed !!
}

res.render('index', {
  items: bankniftydocs,
  niftyitems: niftydocs,
  oidata: masterArry
});

server log
server-log

This is the current handlebar code

<script>
   
  const oidata=[{{oidata}}];
  
  var arrayLength = oidata.length;

  for (var i = 0; i < arrayLength; i++) {
    alert(oidata[i][0]); // no alert
	alert(oidata[i][1]); // no alert
	alert(oidata[i][2]); // no alert
}
 

</script>

In your handlebar template, change the script section to this:

<script>
console.log({{oidata}});
</script>

What is logged to the browser console?

Nothing . Code is not going upto that.

I think issue is with server code. Please see the previous server code, specifically this part

  masterArry[i].push(strikeArr);  // can I write this ?
  masterArry[i].push(callArr);
  masterArry[i].push(putArr);
  console.log(masterArry); **// Log  not printed !!**