3

I have no idea why I'm having so much trouble with this. This seems like it should be really simple.

I have a JavaScript string like the following:

var str = '[[1, 2, 3], [4, 5, 6], [7, 8, 9]]';

I actually want to convert this into an array of arrays. str.split(',') doesn't work because it'll split on the commas in the inner arrays.

I'm sure this conversion is probably something stupidly simple, but I must be missing it. Any help would be appreciated.

JoshG
  • 6,472
  • 2
  • 38
  • 61

2 Answers2

4

The string str confirms to the JSON spec, so it can be parsed with JSON.parse.

var arr = JSON.parse(str);
Amit Joki
  • 58,320
  • 7
  • 77
  • 95
1

var str = '[[1, 2, 3], [4, 5, 6], [7, 8, 9]]';
var arr = JSON.parse("[" + str + "]");

console.log(arr[0][0]); // [1, 2, 3]
console.log(arr[0][0][0]); // 1

You may use JSON.parse, more info here

https://jsfiddle.net/5yz95ktg/

overloading
  • 1,210
  • 4
  • 25
  • 46