How to access node JS array in javascript?

There’s nothing wrong with that code assuming all of the variables in question are arrays.

But TBH, I’ve lost the thread of what’s going on a little and find things like:

strikeArr.push(rowList[j].c[0].v);

hard to parse and prone to errors.

If I was you, I’d go back through your code and log the values of each variable (one by one) until you can localize where the mistake is.

I can help you sort your problem out, but I have no idea what many of the variables, like openinterestdocs, hold.

What would be better is if you can hardcode them (for the purpose of troubleshooting) and post a code snippet here with which I can recreate your problem.

issue is there.

individual arrays are fine.

please see the updated code with console and logs

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("strikeArr=" + rowList[j].c[0].v);
    strikeArr.push(rowList[j].c[0].v);
    console.log("callArr=" + rowList[j].c[1].v);
    callArr.push(rowList[j].c[1].v);
    console.log("putArr" + rowList[j].c[2].v);
    putArr.push(rowList[j].c[2].v);
  }

  console.log("Here # 1");
  masterArry[i].push(strikeArr);
  console.log("Here # 2");
  masterArry[i].push(callArr);
  console.log("Here # 3");
  masterArry[i].push(putArr);
  console.log("Here # 4");
  console.log(masterArry);
}

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

});

LOG

after console.log("Here # 1"); no other logs are printed.

so something wrong with this
masterArry[i].push(strikeArr);

Effectively issue boils down to

console.log("Here # 1"); // This prints
console.log("value of i=" + i);  // This prints
console.log("value of strikeArr=" + strikeArr);  // This prints
masterArry[i].push(strikeArr);  //  what is the trouble here ?
console.log("Here # 2");  // This DOES NOT print

Lol, seriously no idea. It’s valid JS syntax.

for (i = 0; i < openinterestdocs.length; i++) {

Here i is an unintended global. Try fixing that.

okay. I changed that to
for (var i = 0; i < openinterestdocs.length; i++) {

same issue

So no idea why it’s not working. Sorry.

My advice would be to strip away the irrelevant pieces until you get down to the root of your problem. You will either solve the issue yourself, or end up with some minimal code that recreates your issue that you can post here.

I got something.

please see these prints. does these prints look alright ?

console.log("Here # 1"); // This prints
console.log("value of i=" + i);  // This prints
console.log("value of strikeArr=" + strikeArr);  // This prints
console.log("value of masterArry[i]=" + masterArry[i]); **// This prints : value of masterArry[i]=undefined**

masterArry[i].push(strikeArr); // This  DOES NOT print
console.log("Here # 2");

I don’t really know what to say other than masterArry is not what you expect it to be. If masterArry[i] is undefined, then the code won’t run (as you’re experiencing).

const masterArry = [];
masterArry.push([1, 2]);
masterArry[0]
> [ 1, 2 ]

masterArry[0].push(3);
masterArry[0]
> [ 1, 2, 3 ]

masterArry[1]
> undefined
masterArry[1].push(4)
> TypeError: Cannot read property 'push' of undefined

Is there any other collection I can think of here as alternative which can hold my 3 arrays ?
I plan extract these 3 arrays and pass to the chart library in index hbs page

An array can hold other arrays, as can an object literal (or a set, or a map).

The problem is with how you are constructing the data you wish to pass to the template.

Maybe we can sort that out. What does the variable openinterestdocs contain?

But please post just a small sample, not a huge dump.

openinterestdocs is what mongoose returns with a find query from mongodb.

console.log(“openinterestdocs”+openinterestdocs);
this prints
open-interest-console

and here is the equivalent json data in mongo db
open-interest-jason.txt (6.9 KB)

Ok, I edited the JSON a little. Given this:

{
  "_id" : ObjectId("5c1e78fe39601938c3e1480a"),
  "cols" : [
    {
      "label" : "strike_price",
      "type" : "number"
    },
    {
      "label" : "Calls OI Change",
      "type" : "number"
    },
    {
      "label" : "Puts OI Change",
      "type" : "number"
    }
  ],
  "rows" : [
    {
      "c" : [
        {
          "v" : 25700
        },
        {
          "v" : 0
        },
        {
          "v" : 41840
        }
      ]
    },
    {
      "c" : [
        {
          "v" : 25800
        },
        {
          "v" : 60
        },
        {
          "v" : 22620
        }
      ]
    },
    {
      "c" : [
        {
          "v" : 25900
        },
        {
          "v" : 0
        },
        {
          "v" : 37580
        }
      ]
    }
  ]
}

What would you like to pass to the handlebars template?

What would you like to pass to the handlebars template?

I want to construct 3 arrays from this json.

for all c’s

make strikeArr for c[0].v
make callArr for c[1].v
make putArr for c[2].v

Then I want to pass these 3 arrays to handlebars to highcharts chart for plotting a graph.

Here is what my mongoose doing with the find query to get that json record out of mongo db

var colSchema=new Schema({
	label:String,
	type:String
});

var vSchema=new Schema({
	v:String
});
var cSchema=new Schema({
	c:[vSchema]
});

var openInterestDataSchema = new Schema({
	_id: String,
	cols:[colSchema],
	rows:[cSchema],
	
}, {collection: 'bankniftyopeninterest'});



var bankniftyopeninterest = mongoose.model('bankniftyopeninterest', openInterestDataSchema);

bankniftyopeninterest.find().then(function(openinterestdocs) {

// I have posted processing code with openinterestdocs in previous posts

})

OK. And given the data above, what should these arrays look like?

Use the data above, i.e. { "_id" : ObjectId("5c1e78fe39601938c3e1480a"), "cols" : [ ... ]} and provide an example of what you would like to have passed through to the template.

strikeArr=[ 25700 , 25800,25900 , 26000 …]

callArr=[ 0, 60,0, -4600 ,720…]

putArr=[ 41840,22620,37580,-100140,…]

I’d lose the for loops as they are hard to follow. I’d do it like this:

const strikeArr = json.rows.map(obj => obj.c[0].v);
const callArr = json.rows.map(obj => obj.c[1].v);
const putArr = json.rows.map(obj => obj.c[2].v);

Given the same setup as in #14 and the JSON you posted above, this works for me:

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

const json = {
  _id: '5c1e78fe39601938c3e1480a',
  cols: [
    {
      label: 'strike_price',
      type: 'number'
    },
    {
      label: 'Calls OI Change',
      type: 'number'
    },
    {
      label: 'Puts OI Change',
      type: 'number'
    }
  ],
  rows: [
    {
      c: [
        {
          v: 25700
        },
        {
          v: 0
        },
        {
          v: 41840
        }
      ]
    },
    {
      c: [
        {
          v: 25800
        },
        {
          v: 60
        },
        {
          v: 22620
        }
      ]
    },
    {
      c: [
        {
          v: 25900
        },
        {
          v: 0
        },
        {
          v: 37580
        }
      ]
    }
  ]
};

const strikeArr = json.rows.map(obj => obj.c[0].v);
const callArr = json.rows.map(obj => obj.c[1].v);
const putArr = json.rows.map(obj => obj.c[2].v);

app.get('/', (req, res) => {
  res.render('index', { items: { strikeArr, callArr, putArr } });
});

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

index.hbs

<h1>Example App</h1>

<script>
  const strikeArr = [{{ items.strikeArr }}];
  const putArr = [{{ items.putArr }}];
  const callArr = [{{ items.putArr }}];

  alert(strikeArr);
  alert(putArr);
  alert(callArr);
</script>

Does that work for you?

yes. this works for one given json data.

I’ll have 24 such json data.

How do you send to handlebars now ? that is the exact spot where I’m stuck.

Lol, I don’t know what to say. Every time I answer your question, the scope of what you are trying to do shifts.

What does that mean?

Here is the simplest troubled version …

server code

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

How do I access every object in masterArry in handlebar ? this is the trouble.

This does not work.

handlebar code

var masterArr=[{{items}}];
  
  for(int i=0;i<masterArr;i++){
	  
	  console.log("*********callArr*********");
	  console.log(masterArr[i].strikeArr);
	  console.log("*********end*********");
	 
}

It would be better to pass through an object containing your arrays, like I demonstrated in my example.

const strikeArr = json.rows.map(obj => obj.c[0].v);
const callArr = json.rows.map(obj => obj.c[1].v);
const putArr = json.rows.map(obj => obj.c[2].v);

app.get('/', (req, res) => {
  res.render('index', { items: { strikeArr, callArr, putArr } });
});

Then in your template:

const strikeArr = [{{ items.strikeArr }}];
const putArr = [{{ items.putArr }}];
const callArr = [{{ items.putArr }}];

If in doubt, try to log what you are receiving in the template before attempting to do anything with it. For example:

const masterArr=[{{items}}];
console.log(masterArr);

and see what is getting passed through.

I would also spend some time investigating ES6, the console object and transformative array methods which you can use instead of for loops.