2

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]]");
2
  • 2
    There is, and it's exactly as you've shown above. If you ran that code, you'd get a "two dimensional array" (actually, an array of arrays). Note that using eval (in JavaScript) is generally not recommended unless you have absolute trust that the string you're evaling won't contain malicious code, since it actually runs code. So eval("maliciousCodeToWipeYourStorage()") will run that malicious code. But that string is also valid JSON, so you could use JSON.parse instead. Commented Oct 30, 2022 at 10:05
  • 1
    Note: This isn't a Python question, so I've removed the Python tags. Just because you're referring to Python, it doesn't mean that Python tag followers need to have this JavaScript question highlighted for them. Commented Oct 30, 2022 at 10:07

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.