javascript - 如何将mysql的数据行转换为javascript数组?Node.js 应用程序
问题描述
首先,我是新手。毫无疑问,我犯了一些简单的错误。
使用带有 MySQL 数据库的 Node.js,我正在构建一个允许用户登录的基本 Web 应用程序。一旦他们登录,他们将被带到他们的个人资料页面,并以条形图的形式显示他们完成的测验结果。
我想将一行mysql数据转换成一个数组。
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);
}
这就是我实际得到的,它不允许我循环。
行数据包 {
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 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)
参考[第 1 部分]:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values
说明:Object.values() 方法返回给定对象自己的可枚举属性值的数组,其顺序与 for...in 循环提供的顺序相同(不同之处在于 for-in 循环枚举原型链也是如此)。
对于第二部分,计算总分://使用第一部分的值数组
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)
参考[第二部分]:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
描述:reduce() 方法对数组的每个元素执行一个 reducer 函数(由您提供),从而产生一个输出值。
推荐阅读
- python - Pandas 创建具有按时间戳排序的累积链接历史记录的列
- html - 动作伪类悬停不按程序旋转 div
- python - 如何从对 Django-restful-framework 的请求中获取多个值
- javascript - 在 iframe 中嵌入 django 登录
- spring-boot - 如何配置 SpringBoot ObjectMapper
- c++ - CMake Vscode无法调试构建工作正常但调试有问题
- python - 如何确定回调中的python范围
- android - 是否可以在android中添加虚拟相机?
- javascript - 调用函数 (javascript)
- azure-api-management - 使用自定义域名访问内部 VNET 的 API 管理(获取默认 IIS 页面)