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.
asked Aug 21, 2010 at 3:46
Hector Minaya
1,7153 gold badges26 silver badges45 bronze badges
2 Answers 2
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.
answered Aug 21, 2010 at 3:50
Stefan Kendall
68.2k69 gold badges259 silver badges409 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Hector Minaya
My data is not in JSON format, I don't need it in JSON format.
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', '']]");
Timwi
66.8k34 gold badges172 silver badges235 bronze badges
4 Comments
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.
Scott Evernden
no idea why you got the downvote as this is the correct answer
Hector Minaya
Does this create one array with 3 positions data[0], data[1] and data[2] or a multidimensional array?
Hector Minaya
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.
Explore related questions
See similar questions with these tags.
lang-js