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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With