Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string representation of JavaScript array to object [duplicate]

Is there some javascript function that can take a string already formatted as an array, and casts it as an array?

var some_string = "[1,2,3,4]";
var some_array = castAsArray(some_string);
some_array.length // Returns 4.
like image 921
Don P Avatar asked Dec 13 '25 00:12

Don P


2 Answers

What you're looking for is JSON.parse(). It'll take any string that represents a valid JavaScript object in JSON (JavaScript Object Notation), and convert it to an object.

var some_string = "[1,2,3,4]";
var some_array = JSON.parse(some_string);
some_array.length // Returns 4.
like image 188
Sam Hanley Avatar answered Dec 15 '25 12:12

Sam Hanley


Even eval will do the trick. Using eval, is not good practice but it is just a suggestion.

a="[1,2,3,4]"
b=eval(a)

Understand that using eval is always a bad idea (always means at most of the cases) and this is one excellent SO question and answers discussing this.

Eval-Don't use it.

like image 21
Jack_of_All_Trades Avatar answered Dec 15 '25 14:12

Jack_of_All_Trades



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!