how to pass data from node.js to local javascript, keeping array capabilities?
const query = db.query(sql, post, (err, results) => {
if (err) {
throw err;
} else if (results.length >= 1) {
console.log(results);
const listResults = [];
for (let i = 0; i < results.length; i++) {
listResults.push(results[i].ENwords);
listResults.push(results[i].PLwords);
}
res.render('flashcards', {layout: 'flashcards', listResults});
in flashcard.ejs:
<script>
let listWords = <%= listResults %>;
console.log(listWords);
</script>
I get an error that the first item in the list is "is not defined".
I’ve also tried this. This works but the value is no longer an array:
<script>
let listWords = "<%= listResults %>";
console.log(listWords);
</script>
In this particular case, reworking these values is pointless, because different data are stored there and it is not possible to divide them in an appropriate way to make a new list.
>Solution :
Stringify the array in Node.js
let listWords = <%= JSON.stringify(listResults) %>;
JSON.stringify creates a JSON representation of the string and JSON can be used as array literal.