-5

I have string that looks something like this:

var stringArray = "[[1,2,3,4],[5,6,7,8]]"

I need to convert it using javascript so it is like this:

var actualArray = [[1,2,3,4],[5,6,7,8]]

How would one achieve this?

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Alex Chiu
  • 7
  • 2

1 Answers1

-1

Your input is structured as JSON. You can thus simply use any JSON parsing method or library. For example JSON.parse(stringArray) (documentation).

Here is a snippet which uses JSON.parse:

var stringArray = "[[1,2,3,4],[5,6,7,8]]";
var parsedArray = JSON.parse(stringArray);

$('#first').html(parsedArray[0].toString());
$('#second').html(parsedArray[1].toString());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
First element: <span id="first"></span><br>
Second element: <span id="second"></span>

You can also use the eval function (documentation) but please note that you should avoid that function at all cost if possible. It is dangerous and often slower than its alternatives. Here is more on that.

However here is a version using the eval method:

var stringArray = "[[1,2,3,4],[5,6,7,8]]";
var parsedArray = eval(stringArray);

$('#first').html(parsedArray[0].toString());
$('#second').html(parsedArray[1].toString());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
First element: <span id="first"></span><br>
Second element: <span id="second"></span>
Zabuzard
  • 25,064
  • 8
  • 58
  • 82
  • 1
    Thanks for the swift replies , both eval() and JSON.parse work great. – Alex Chiu Oct 21 '17 at 22:40
  • 2
    [eval()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) should only be used when absolutely needed. Any values used must be sanitized. – Alan Larimer Oct 21 '17 at 23:09
  • @AlanLarimer Thanks for the link, I've edited the answer, included it and changed the order of suggestions. – Zabuzard Oct 21 '17 at 23:18