Reputation: 18343
In order to convert string into 1-dimensional JavaScript array I could use 'eval()'. But how to convert string into 2-dimensional array?
My string is:
['stage 1', 1, 11, 111],['Stage 2', 2, 22, 222]
Execution "eval(...)" with such parameter creates a 1 array with 4 elements: ['stage', 1, 11, 111]. Instead I would like to have array of 2 elements, where each element in turn is another array of 4 elements.
I believe, I could split original string by ',' into list of substrings and call 'eval' for each of them and combine the result into a 2-dimensional array.
But I believe that more efficient way should already exist. Is there any? If yes, please advise.
Thank you very much in advance!
Upvotes: 1
Views: 2894
Reputation: 74204
Instead of using eval
it would be better to use JSON.parse
:
var string = '["stage 1", 1, 11, 111],["Stage 2", 2, 22, 222]';
var array2d = JSON.parse("[" + string + "]");
console.log(array2d);
See the demo here: http://jsfiddle.net/y94zz/
Upvotes: 3