views:

38

answers:

2

I have a function which receives a string parameter, I need to convert this into an array. For example:

var param = "['Presidente', '', ''], ['Gerente de Operaciones', 'Presidente', ''], ['Gerente de Ventas', 'Presidente', '']";

function myFunc(data){
  // DoSomethingHere
}

myFunc(param);

I need to convert data into an array, in this case it would have 3 positions. I tried doing Split() but didn't get very far.

+1  A: 

You can do it with eval(). Just wrap your contents inside an extra "[ ]" to make it an array

Like so:

var data = eval("[['Presidente', '', ''], ['Gerente de Operaciones', 'Presidente', ''], ['Gerente de Ventas', 'Presidente', '']]");
Dan Harris
Ok, I'm sure I was downvoted because "eval is evil".. Using Crockford's json2.js to .parse() it is safer if you are planning on working on untrusted values in a browser.
Dan Harris
no idea why you got the downvote as this is the correct answer
Scott Evernden
Does this create one array with 3 positions data[0], data[1] and data[2] or a multidimensional array?
hminaya
Thanks, this was exactly what I was looking for it works like charm. I'm not working with any untrusted values, so that isn't a problem.
hminaya
+3  A: 
param = "[" + param + "]";
var array = JSON.parse( param );

First, make the object correct, and then use a json parser of some kind to parse the string.

Stefan Kendall
My data is not in JSON format, I don't need it in JSON format.
hminaya
...yes it is. Almost.
Stefan Kendall