24

i have a string

var traingIds = "${triningIdArray}";  // ${triningIdArray} this value getting from server 
alert(traingIds)  // alerts [1,2]
var type = typeof(traingIds ) 
alert(type)   // // alerts String

now i want to convert this to array so that i can iterate

i tried

var trainindIdArray = traingIds.split(',');
$.each(trainindIdArray, function(index, value) { 
    alert(index + ': ' + value);   // alerts 0:[1 ,  and  1:2]
});

how to resolve this?

maaz
  • 3,190
  • 18
  • 55
  • 95

4 Answers4

74

Since array literal notation is still valid JSON, you can use JSON.parse() to convert that string into an array, and from there, use it's values.

var test = "[1,2]";
parsedTest = JSON.parse(test); //an array [1,2]

//access like and array
console.log(parsedTest[0]); //1
console.log(parsedTest[1]); //2
Joseph
  • 113,089
  • 28
  • 177
  • 225
  • Wow, this is just brilliant... and simple Thank you. – Watercayman Feb 19 '20 at 23:57
  • 1
    I have input just like OPs, except the var is set to the .attr() of my element. It has `typeof string` and looks like `"['foo','bar']"`. When I try JSON.parse i get the `Uncaught SyntaxError: Unexpected token ' in JSON at position 1 at JSON.parse ()` error. Any idea? – KuboMD Jun 05 '20 at 21:03
13

Change

var trainindIdArray = traingIds.split(',');

to

var trainindIdArray = traingIds.replace("[","").replace("]","").split(',');

That will basically remove [ and ] and then split the string

Clyde Lobo
  • 9,033
  • 7
  • 35
  • 61
11

Assuming, as seems to be the case, ${triningIdArray} is a server-side placeholder that is replaced with JS array-literal syntax, just lose the quotes. So:

var traingIds = ${triningIdArray};

not

var traingIds = "${triningIdArray}";
Mitya
  • 32,084
  • 8
  • 49
  • 92
5

check this out :)

var traingIds = "[1,2]";  // ${triningIdArray} this value getting from server 
alert(traingIds);  // alerts [1,2]
var type = typeof(traingIds);
alert(type);   // // alerts String

//remove square brackets
traingIds = traingIds.replace('[','');
traingIds = traingIds.replace(']','');
alert(traingIds);  // alerts 1,2        
var trainindIdArray = traingIds.split(',');

​for(i = 0; i< trainindIdArray.length; i++){
    alert(trainindIdArray[i]); //outputs individual numbers in array
    }​ 
Clayton
  • 446
  • 2
  • 8
  • 2
    You can use eval. eg. eval("[1,2]") # => [1,2] – Sam Kah Chiin Dec 19 '16 at 06:50
  • It surprises me @Sam Kah Chiin 's comment is not an answer. It really a great deal to this question. it is single lined and simple. Thanks – Young Emil Feb 04 '18 at 12:37
  • 1
    @YoungMillie, actually using `eval` in javascript can be dangerous as improper use of eval opens up your code for injection attacks. Check this [stackoverflow](https://stackoverflow.com/questions/86513/why-is-using-the-javascript-eval-function-a-bad-idea) :) – Sam Kah Chiin Feb 06 '18 at 07:34
  • Thanks @Sam Kah Chiin , knowledge is power. I now understand what eval is and how dangerous it can be. – Young Emil Feb 06 '18 at 08:20
  • Then in that case...I guess @Clayton 's answer is also a good way around the problem. – Young Emil Feb 06 '18 at 08:27