Struggling with managing JavaScript objects...
Currently, I am working on generating a Google Chart based on user selections. The process involves two multi-select lists that construct an object as shown below:
$('option:selected', $('#slChartSettingsEntities')).each(function () {
var el1 = $(this);
$('option:selected', $('#slChartSettingsStats')).each(function () {
var el2 = $(this);
dashParms.items.push({
entityid: el1.val(),
statid: el2.val(),
entityname: el1.text(),
statname: el2.text()
});
});
});
The dashParms
object is then used to define columns for the chart like this:
// Preliminary setup:
var seriesCount = 0; // I want to optimize this
var data = new google.visualization.DataTable();
data.addColumn({ id: 'date', label: 'Date', type: 'date' });
data.addColumn({ id: result.companyName, label: result.companyName, type: 'number' });
if ($('#cbxEtc').is(':checked')) {
data.addColumn({ id: 'ave', label: 'Company Average', type: 'number' });
seriesCount++; // working to improve this
}
// Key aspect:
for (var j = 0; j < dashParms.items.length; ++j) {
data.addColumn({
id: (dashParms.items[j].entityid + '#' + dashParms.items[j].statid),
label: (dashParms.items[j].entityname + ' (' + dashParms.items[j].statname + ')'),
type: 'number'
});
seriesCount++; // working to improve this
}
I send the dashParms
to the server and receive back the data (a C# List<List<object>>
; detailed demonstration available but not necessary) which is then used to populate the chart rows:
var jsonResult = $.parseJSON(result.chartData);
if (seriesCount == 0) {
$.each(jsonResult, function (k, v) {
data.addRow([
new Date(v[0], 0, 1),
v[1]
]);
});
}
else if (seriesCount == 1) {
$.each(jsonResult, function (k, v) {
data.addRow([
new Date(v[0], 0, 1),
v[1],
v[2]
]);
});
}
else if (seriesCount == 2) {
$.each(jsonResult, function (k, v) {
data.addRow([
new Date(v[0], 0, 1),
v[1],
v[2],
v[3]
]);
});
}
else if (seriesCount == 3) {
// etc etc etc
}
The process is repeated for configuring the chart object:
if (seriesCount == 0) {
chartcfg = {
'chartType': 'ComboChart',
'options': {
'seriesType': 'bars'
}
};
}
else if (seriesCount == 1) {
chartcfg = {
'chartType': 'ComboChart',
'options': {
'seriesType': 'bars',
'series': {
1: { type: 'line', tooltip: true }
}
}
};
}
else if (seriesCount == 2) {
chartcfg = {
'chartType': 'ComboChart',
'options': {
'seriesType': 'bars',
'series': {
1: { type: 'line', tooltip: true },
2: { type: 'line', tooltip: true }
}
}
};
}
else if (seriesCount == 3) {
// etc etc etc
}
Seeking advice on refactoring to dynamically create these objects and avoid excessive conditional statements. The main focus is on 1) creating the array for data.addRow()
, and 2) generating the chartcfg
JSON object.