Reputation: 172
I have a multidimensional array in javascript that I would like to be able to turn into a string while preserving brackets. I have taken a look at other questions such as javascript - Convert array to string while preserving brackets and the answers there didn't help me much.
My array could look like the following:
[[[0,0,1],1],[[1,0,0],4],[[1,0,1],5], [[0,1,1],3],[[1,1,0],6],[[0,1,0],2]]
When I print the array I see:
0,0,1,1,1,0,0,4,1,0,1,5,0,1,1,3,1,1,0,6,0,1,0,2
The output that I am expecting is what the original array looks like.
I have also tried the following code:
alert("[[" + myArray.join("],[") + "]]");
This works for almost everything, I get an output of:
[[0,0,1,1],[1,0,0,4],[1,0,1,5], ...
And I would like to see what the origional array looks like with the brackets. I would also like to stay away from JSON.stringify(); and JSON.parse();
Upvotes: 0
Views: 498
Reputation: 265171
JSON.stringify()
and JSON.parse()
will do exactly what you ask for. Try it out:
var arr = [[[0,0,1],1],[[1,0,0],4],[[1,0,1],5], [[0,1,1],3],[[1,1,0],6],[[0,1,0],2]];
var str = JSON.stringify(arr);
alert(str);
var parsed = JSON.parse(str);
alert(parsed);
console.log(parsed);
Upvotes: 1