Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to pass data from node.js to local javascript, keeping array capabilities?

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".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading