In Javascript, I have a string that I need to convert to an Array of objects.
//ORIGINAL STRING :
var originalString = "[13, "2017-05-22 17:02:56", "Text111"], [25, "2017-05-22 17:03:03", "Text222"], [89, "2017-05-22 17:03:14","Text333"]";
I need to be able to loop through each object, and get the 3 properties by using indexes. That would give (for the first Array) :
myItem[0] => 13
myItem[1] => "2017-05-22 17:02:56"
myItem[2] => "Text111"
That first sounded simple to my head (and probably is), but after several attempts, I am still stuck.
Please note that I cannot use jQuery because running with a very old Javascript specification : "Microsoft JScript", which is EcmaScript 3 compliant.
I thank you ;)
If you just could use
JSON.parse
, then you would be able to append[
and]
to the beginning and ending of a string respectively, and then parse it as an array of arrays.However, as far as I know,
JSON.parse
is not ECMAScript 3 complaint, so you will have to parse it yourself.Something like this should help:
I am not quite sure what functionality exists in ECMAScript 3 and I used MDN for this. It looks like many functions even like
String.prototype.trim
do not exist in ECMAScript 3. So I had to reimplement it myself. If I am wrong and you can use them in JScript, then just use some of these functions instead.The general idea of algorithm is the following:
Note that all values are threaded as strings in this solution.
It could be rewritten in a recursive way instead of looping if you have more nested levels, but it would be less understandable - I just have provided a minimal solution which works :) I am sure you can improve it in many ways.