Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to a multidimensional array

I have a string

 var myString = "['Item', 'Count'],['iPad',2],['Android',1]";

I need to convert it into an array where:

myArray[0][0] = 'Item';
myArray[0][1] = 'Count';
myArray[1][0] = 'iPad';
myArray[1][1] = 2;

etc...

The string can vary in length but will always be in the format above. I have tried splitting and splicing and any other "ing" I can think of but I can't get it.

Can anyone help please?

like image 927
Fred Avatar asked Nov 29 '12 16:11

Fred


1 Answers

If the string is certain to be secure, the simplest would be to concatenat [ and ] to the beginning and end, and then eval it.

var arr = eval("[" + myString + "]");

If you wanted greater safety, use double quotes for your strings, and use JSON.parse() in the same way.

var myString = '["Item", "Count"],["iPad",2],["Android",1]';

var arr = JSON.parse("[" + myString + "]");

This will limit you to supported JSON data types, but given your example string, it'll work fine.

like image 53
I Hate Lazy Avatar answered Sep 28 '22 23:09

I Hate Lazy