-2

How can we convert an array of type string back into array.

var arr = '[ "abc", "def"]';
console.log(typeof arr)    ==> String

How can i convert it back into an array?

I am getting this array in form of string from an API response. and these are errors which can be multiple. I want to convert them into an array such that i can display them on their correct positions.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Aman Gupta
  • 1,764
  • 4
  • 30
  • 58
  • 2
    When programming, it's important to always ask why you're doing what you're doing. `JSON.parse(arr)`. But, why is `arr` a String in the first place? My guess... bad practice. – StackSlave Apr 18 '17 at 06:14
  • @T.J.Crowder Thanks. Corrected that. – Aman Gupta Apr 18 '17 at 06:15
  • 1
    I think @PHPglue is saying something along the lines of the [XY problem](https://meta.stackexchange.com/a/66378/293552). – John Apr 18 '17 at 06:15
  • Possible duplicate of [Javascript how to parse JSON array](http://stackoverflow.com/questions/9991805/javascript-how-to-parse-json-array) – Alexei Levenkov Apr 19 '17 at 02:53

4 Answers4

0

If your string is really as shown in your edit (not your original question), it's valid JSON, so you could use JSON.parse:

var str = '["abc", "def"]';
var arr = JSON.parse(str);
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

Since your array syntax conforms to that of a JSON array: Use a JSON parser.

Browsers have one built-in these days.

arr = JSON.parse(arr);

For a more general approach, you would need to look at eval, but that has numerous drawbacks (including issues of scope, speed, and security).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

You can't convert it back, since you don't actually have an array.

an array should be created without the single quotes ... you are creating a string, you want to do something like the following if you want to create an array.

var arr = ["string 1","string 2"];

UPDATE Since you updated your question, with information regarding why you had a string, you can follow the suggested solution:

JSON.parse(arr);
Gary
  • 602
  • 9
  • 7
0

Use JSON.parse() to convert the JSON string into JSON object.

DEMO

var arr = '[ "abc", "def"]';
console.log(typeof arr); // string

var arr = JSON.parse('[ "abc", "def"]');
console.log(typeof arr); // object
Debug Diva
  • 26,058
  • 13
  • 70
  • 123