下划线转驼峰方法
function camelCaseKeys(obj) {
const result = {};
for (let key in obj) {
let newKey = key[0].toLowerCase() + key.slice(1).replace(/_([a-z])/g, function($0,$1){return $1.toUpperCase();});
result[newKey] = obj[key];
}
return result;
}
?转换代码
rows = rows.map(item => camelCaseKeys(item));
完整代码如下:?
const mysql = require('mysql')
const pool = mysql.createPool({
host: '127.0.0.1',
user: 'root',
password: '123456',
database: 'lzwj_data',
port: 3306
})
function camelCaseKeys(obj) {
const result = {};
for (let key in obj) {
let newKey = key[0].toLowerCase() + key.slice(1).replace(/_([a-z])/g, function($0,$1){return $1.toUpperCase();});
result[newKey] = obj[key];
}
return result;
}
let query = function( sql, values ) {
// 返回一个 Promise
return new Promise(( resolve, reject ) => {
pool.getConnection(function(err, connection) {
if (err) {
reject( err )
} else {
connection.query(sql, values, ( err, rows) => {
if ( err ) {
reject( err )
} else {
rows = rows.map(item => camelCaseKeys(item));
resolve( rows )
}
// 结束会话
connection.release()
})
}
})
})
}
module.exports = query
转换前
转换后
?