我已经写了以下内容来重新格式化我的sql数据以适应融合图表可读格式。现在,我已经发声了#39;并且我正在返回正确的格式,我显然采取了漫长的路线。从数据库重建的优雅或有效/适当的方法是什么?
var chartData = {
chart: {},
categories: [],
dataset: []
};
var category = [];
var dataseries1 = [];
var dataseries2 = [];
var dataseries3 = [];
connection.connect();
connection.query('SELECT * from garage', function(error, results, fields) {
if (error) throw error;
for (var i = 0, len = results.length; i < len; i++) {
category.push({
label: results[i].date
});
dataseries1.push({
value: results[i].humidity
});
dataseries2.push({
value: results[i].temperature
});
dataseries3.push({
value: results[i].absolute_humidity
});
}
chartData.categories.push({
category: category
});
chartData.dataset.push({
seriesname: 'Humidity',
data: dataseries1
});
chartData.dataset.push({
seriesname: 'Temperature',
data: dataseries2
});
chartData.dataset.push({
seriesname: 'Absolute Humidity',
data: dataseries3
});
console.log(chartData);
});
编辑:返回的格式是
{ chart: {},
categories: [ { category: [Array] } ],
dataset:
[ { seriesname: 'Humidity', data: [Array] },
{ seriesname: 'Temperature', data: [Array] },
{ seriesname: 'Absolute Humidity', data: [Array] } ] }
答案 0 :(得分:1)
您的代码太忙于将数据从一个临时位置移动到另一个临时位置。这就是我要做的。
辅助函数(这已经包含在许多JS工具带库中,如lodash):
function pluck(property, items) {
return items.map(function (item) { return item[property]; });
}
用法:
connection.connect();
connection.query('SELECT * from garage', function (err, results) {
if (err) throw err;
var chart = new FusionCharts({
// ...
dataSource: {
categories: pluck('date', results),
dataset: [
{ seriesname: 'Humidity', data: pluck('humidity', results) },
{ seriesname: 'Temperature', data: pluck('temperature', results) },
{ seriesname: 'Absolute Humidity', data: pluck('absolute_humidity', results) }
]
}
});
chart.render();
});
当您拥有ES6 arrow-function support时,如果您愿意,可以按如下方式重写pluck
帮助程序。
var pluck = (property, items) => items.map(item => item[property]);