May 29, 2015

convert string array to object array highchart and json

Code Demon’s Question:

I have this script

var portfolio_in_arrears = [];
var portfolio_future = [];
var portfolio_good_standing = [];
var portfolio_ingrace_period = [];

$.each(JSON.parse(response.portfolio), function(index, value){
    portfolio_in_arrears.push(value.in_arrears);
    portfolio_future.push(value.future_clients);
    portfolio_good_standing.push(value.good_standing);
    portfolio_ingrace_period.push(value.grace_period);
});

and this part of the highchart options

series: [{
    name: 'Future',
    data: portfolio_future //sample [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
    }, {
    name: 'In Grace Period',
    data: portfolio_ingrace_period //sample [-0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8, 24.1, 20.1, 14.1, 8.6, 2.5]
    }, {
    name: 'Arrears',
    data: portfolio_in_arrears //sample [-0.9, 0.6, 3.5, 8.4, 13.5, 17.0, 18.6, 17.9, 14.3, 9.0, 3.9, 1.0]
    }, {
    name: 'Good standing',
    data: portfolio_good_standing //sample [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]
}]

I did successfully retrieved and parse the data from the json response and put on there corresponding array

var portfolio_in_arrears = [];
var portfolio_future = [];
var portfolio_good_standing = [];
var portfolio_ingrace_period = [];

but sadly when i tried to bind those array on the series option, it didnt work. When i check it on the console e.g. console.log(portfolio_future), I see the array like this

["146", "143", "123", "106", "106", "94", "76", "71", "69", "83", "66", "66", "98", "98", "96", "90", "85", "102", "102", "94", "135", "126", "111", "125", "116", "116", "108", "129", "113", "93", "102", "86", "86", "68", "81"]

which the proper array for the series option is

[3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]

so any ideas how to turn this

["146", "143", "123", "106", "106", "94", "76", "71", "69", "83", "66", "66", "98", "98", "96", "90", "85", "102", "102", "94", "135", "126", "111", "125", "116", "116", "108", "129", "113", "93", "102", "86", "86", "68", "81"]

to

[146, 143, 123, 106, 106, 94, 76, 71, 69, 83, 66, 66, 98, 98, 96, 90, 85, 102, 102, 94, 135, 126, 111, 125, 116, 116, 108, 129, 113, 93, 102, 86, 86, 68, 81]

as you can see, there’s no double qoutes stuff on each of the number.

You can solve this by specifying the value is strictly numeric. Use parseInt() function

Here is how you would use it.

portfolio_in_arrears.push(parseInt(value.in_arrears));

An example here.

...

Please fill the form - I will response as fast as I can!