Converting an array string to a javascript array

0

I have a data that comes as a parameter of a function.

[['local','precipitação'],['RJ',0.2],['SP',0.8],['MG','']]

This data should be recognized as an array, but javascript recognizes it as a string. Is there any way to convert to an array?

    
asked by anonymous 28.09.2015 / 15:17

1 answer

1

To convert the string "[['local','precipitação'],['RJ',0.2],['SP',0.8],['MG','']]" to an Array you can use eval() .

var s = "[['local','precipitação'],['RJ',0.2],['SP',0.8],['MG','']]";
var a = eval(s);

Some will say that using eval is bad practice, because of the risk of code injection, difficulty debugging etc.

A little better would be to use JSON.parse() . However it seems that it does not accept single quotation marks. In that case it would look something like this:

var s = '[["local","precipitação"],["RJ",0.2],["SP",0.8],["MG",""]]';
var a = JSON.parse(s);

Anyway the best would be to avoid using string unnecessarily, and pass the argument directly as Array.

    
28.09.2015 / 17:06