user3165675 user3165675 - 1 year ago 48
Javascript Question

Highcharts: convert string to an object with javascript

I am querying data from a webservice and in the next step I try to parse the data in a format that is sufficient for highcharts:

var aData = response.d;
var arr = [];

for (i = 0; i < aData.length; i++) {
arr.push("["+[aData[i].FileDate2.replace("/Date(", "").replace(")/", ""), aData[i].AutoReleasedPct]+"]");
}
arr = "[" + arr + "]";
//alert(arr);


When I alert the result, i get this:

[[1502920800000, 85.714285714285], [1502834400000, 82.022471910112], [1502748000000, 100], [1502488800000, 100], [1502402400000, 100], [1502316000000, 100], [1502229600000, 94], [1502143200000, 96.774193548387]]

However, for some reason it doesn't work when I push
arr
to a highchart container. But it works when I copy the result and create an object

dataseries3 = [[1502920800000, 85.714285714285], [1502834400000, 82.022471910112], [1502748000000, 100], [1502488800000, 100], [1502402400000, 100], [1502316000000, 100], [1502229600000, 94], [1502143200000, 96.774193548387]];


and then push it to highcharts by
ccontainer2(dataseries3);


Why there is a difference between this methods? Its actually exactly the same?

Answer Source

In your function you created only a string which looks like this:

"[elem1,elem2]"

But you need an array object in order to render the highchart.

For this, you can use JSON.parse() method.

JSON.parse method turns a string(json) into a javascript object.

Short example:

var string="[[1,2],[3,4]]";
var array = JSON.parse(string);
console.log(array);

You have to use it in the following way:

ccontainer2(JSON.parse(arr));

Another method is to create directly an array.

var aData = response.d;
var arr = [];

for (i = 0; i < aData.length; i++) {
    arr.push([aData[i].FileDate2.replace("/Date(", "").replace(")/", ""), aData[i].AutoReleasedPct]);
} 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download