I am dynamically generating json data as below
<script>
$(document).ready(function() {
len = "<%- gsdata.length %>"
for ( i = 0; i < len; i++) {
//window.alert(len);
var data = {
"Results": [{
"SCRIP": gsdata[i].SCRIP,
"LTP": gsdata[i].LTP,
"ALERT": gsdata[i].CAMARILLA,
"TRIGERP": gsdata[i].ALERT,
"BOOKAT": gsdata[i].BOOKAT,
"PROFIT": gsdata[i].PROFIT,
}]
}
}
$('#scrip-data').DataTable({
data: data.Results,
columns: [
{data: "SCRIP"},
{data: "LTP"},
{data: "ALERT"},
{data: "TRIGERP"},
{data: "BOOKAT"},
{data: "PROFIT"},
],
});
} );
</script>
This is an ejs template and loop is inside <script> tags. I am not able to get the value of i in the "SCRIP": "<%- gsdata[i].XXX %>". with "SCRIP": "<%- gsdata[1].SCRIP %>" I am able to get the values.
Any help here please
I am guessing (i don't kow ejs), but i would think that you need to indicate that the for loop is part of the template, and not part of the script tag "output" :
<script>
$(document).ready(function() {
len = "<%- gsdata.length %>"
//window.alert(len);
var data = {
"Results": [
<%- for (var i = 0; i < gsdata.length; i++) { %>
{
"SCRIP": "<%- gsdata[i].SCRIP %>",
"LTP": "<%- gsdata[i].LTP %>",
"ALERT": "<%- gsdata[i].CAMARILLA %>",
"TRIGERP": "<%- gsdata[i].ALERT %>",
"BOOKAT": "<%- gsdata[i].BOOKAT %>",
"PROFIT": "<%- gsdata[i].PROFIT %>",
},
<%- } %>
]
}
</script>
Updated to what I think poster is looking for... guessing though.
You don't need to use EJS syntax inside JavaScript.
And you shouldn't call JSON.stringify() to get the length of the array. That returns the length of the serialized array.
$(document).ready(function() {
var len = gsdata.length;
for (var i = 0; i < len; i++) {
//window.alert(len);
var data = {
"Results": [{
"SCRIP": gsdata[i].SCRIP,
"LTP": gsdata[i].LTP,
"ALERT": gsdata[i].CAMARILLA,
"TRIGERP": gsdata[i].ALERT,
"BOOKAT": gsdata[i].BOOKAT,
"PROFIT": gsdata[i].PROFIT,
}]
}
}