0

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.

2 Answers 2

4
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.

1
  • My data is not in JSON format, I don't need it in JSON format. Commented Aug 22, 2010 at 16:56
3

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', '']]");
4
  • 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. Commented Aug 21, 2010 at 3:54
  • no idea why you got the downvote as this is the correct answer Commented Aug 21, 2010 at 3:57
  • Does this create one array with 3 positions data[0], data[1] and data[2] or a multidimensional array? Commented Aug 21, 2010 at 14:48
  • 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. Commented Aug 21, 2010 at 14:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.