简体   繁体   中英

How to convert mysql row of data into a javascript array? Node.js app

First, I'm a newbie. No doubt, I've made some simple errors.

Using Node.js with MySQL Database, I'm building a basic web app that allows users to login. Once they've logged in they will be brought to their profile page and are displayed results of a quiz they've done in the form of a bar chart.

I want covert a row of mysql data into an array.

const mysql = require('mysql');
const dbconfig = require('/config/database');
const connection = mysql.createConnection(dbconfig.connection);
connection.query('USE ' + dbconfig.database);

// Create an array of scores for each category depedning on the user who's 
// loggedin.

var category1scoreQuery = 
"SELECT c1q1, c1q2, c1q3, c1q4, c1q5, c1q6, c1q7, c1q8 
FROM nodejs_login.assessment_score 
AS a JOIN users as u ON a.respondent_id = u.user_respondent_id 
WHERE a.respondent_id = user.user_respondent_id;";

connection.connect(function(err){
    if (err) throw err;

    connection.query(category1scoreQuery, function(err, result, fields) {
        if (err) throw err;

        Object.keys(result).forEach(function(key){
            var cat1Array = result[key];

  // want to return array e.g. ["45/60", "60/60", "40/40","30/40","15/20", 
  // "30/40", "30/60", "20/40"];

             console.log(cat1Array);
        })
    })
});

// I want to convert it to an array to parse the array of strings into 
// totalUserScore over maxCategoryScore

var i;
var userCategoryScore1 = 0;
var maxCategoryScore = 0;

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

var splitScore = cat1Array[i].split("/");
console.log(splitScore);

myQuestionScore = parseInt(splitScore[0], 10);
userCategoryScore1 += myQuestionScore;
console.log(userCategoryScore);

maxQuestionScore = parseInt(splitScore[1]);
maxCategoryScore = maxCategoryScore + maxQuestionScore;
console.log(maxCategoryScore);
}

This is what I am actually getting which doesn't allow me to loop through.

RowDataPacket {

c1q1: '15/60',

c1q2: '15/60',

c1q3: '10/40',

c1q4: '10/40',

c1q5: '5/20',

c1q6: '10/40',

c1q7: '15/60',

c1q8: '10/40' }

This should work for you:

 const RowDataPacket= {

    c1q1: '15/60',

    c1q2: '15/60',

    c1q3: '10/40',

    c1q4: '10/40',

    c1q5: '5/20',

    c1q6: '10/40',

    c1q7: '15/60',

    c1q8: '10/40' }

const values=Object.values(RowDataPacket);
console.log(values)

Reference[1st part] : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values

Description: The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

For the second part, to calculate the total scores: //using the values array from first part

const scores=values.reduce((accum,value)=>{
  const splitValues=value.split('/')
  return {
    score:accum.score + parseInt(splitValues[0]),
     maxScore:accum.maxScore + parseInt(splitValues[1]),
  }
},{score:0,maxScore:0})
console.log(scores)

Reference[2nd part]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

Description: The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

This is fairly common problem when interacting with a database through javascript. To get what you want you can try using JSON library like this:

usersRows = JSON.parse(JSON.stringify(result));

Also this isn't exactly related to your question but it's something that made my life a lot easier when I was doing this: consider using the node Promisify module to transform your queries into promises (from here: https://www.npmjs.com/package/util-promisify ). That way instead of having to use callbacks like you are doing your code would look something like this:

var results = await connection.query(category1scoreQuery); 
//Process results here

Again this is only a suggestion but something that I found was very useful.

Cheers!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM