Home > database >  JavaScript: How to convert a string to a 2D array
JavaScript: How to convert a string to a 2D array

Time:10-30

I have a String value as input that contains a 2-dimensional array in the following format:

"[[1,0,1,1],[0,1,0,1],[1,0,1,1],[0,1,0,1]]"

Also, I need to build the actual multidimensional array and store it in a new variable.

var arr = [[1,0,1,1],[0,1,0,1],[1,0,1,1],[0,1,0,1]];

I know I can traverse the String or even use Regular Expressions to build the array. But I wonder if there is any function similar to eval() in Python to convert the String to an equivalent JS array object directly (despite being a slow process).

var arr = eval("[[1,0,1,1],[0,1,0,1],[1,0,1,1],[0,1,0,1]]");

CodePudding user response:

Considering you have it stored like this

let x = "[[1,0,1,1],[0,1,0,1],[1,0,1,1],[0,1,0,1]]"

let arr = JSON.parse(x)

You array is a valid json that can be parsed and manipulated

let x = "[[1,0,1,1],[0,1,0,1],[1,0,1,1],[0,1,0,1]]"
let arr = JSON.parse(x);
console.log(arr)

Beware that if the string is not a valid json the above code will fail

  • Related