Tigther code - javascript object array

Posted by Scott Silvi on Stack Overflow See other posts from Stack Overflow or by Scott Silvi
Published on 2011-03-01T07:09:35Z Indexed on 2011/03/01 7:24 UTC
Read the original article Hit count: 101

Filed under:
|

Inside the callback 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]   
}
]

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery