Tigther code - javascript object array
Inside the cal开发者_如何学Clback of a $.getJSON call, I have the code outlined below. The first for block aggregates 'total' & assigns values to sov[i]. The map function calculates the percentage of total. I then instantiate a variable called sovData.
With the jQuery Flot graph, any objects that are empty aren't added to the pie chart, so this works for up to 7 different slices/datasets. What I'd like to do is only initialize the ones I need (e.g. sovData would have up to 'howMany - 1' (kws.length -1 ) objects inside of it, likely via something similar to dashboards[i] & sov[i]. How would I do this?
Code:
var sov = [], howMany = kws.length, total = 0, i = 0;
for ( i; i < howMany; i++) {
total += sov[ i ] = +parseInt(data.sov['sov' + ( i+1 ) ],10) || 0;
}
var dashboards = data.dashboards;
sov = $.map( sov, function(v) {
var s = Math.round( ( (v / total) * 10e3 ) / 100);
return s < 1 ? 1 : s;
});
var sovData = [{
label : dashboards[0],
data : sov[0]
},
{
label : dashboards[1],
data : sov[1]
},
{
label : dashboards[2],
data : sov[2]
},
{
label : dashboards[3],
data : sov[3]
},
{
label : dashboards[4],
data : sov[4]
},
{
label : dashboards[5],
data : sov[5]
},
{
label : dashboards[6],
data : sov[6]
}
]
use
var sovData = [];
for (var i = 0; i < howMany-1; i++) {
sovData.push({
label: dashboards[i],
data: sov[i]
});
}
theoretical demo: http://jsfiddle.net/gaby/qN3WY/
精彩评论