Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: push array values from string variable

Tags:

javascript

So as the title says, I'm trying to set an array from a string variable.

/*** THIS DOES NOT WORK ***/
var Multi = [];
var test = "[0,1],[1,5],[2,3],[3,10]";
Multi.push(test);


/*** THIS WORKS ***/
var Multi = [];
Multi.push([0,1],[1,5],[2,3],[3,10]);

Why is it that when I save it as a string it doesn't work? I need for it to work in a string as I'm pulling these values from another PHP file via AJAX.

Thanks.

like image 231
Jonny07 Avatar asked Apr 06 '26 07:04

Jonny07


1 Answers

You can convert your string to valid JSON by adding [ to the front and ] to the back, and then use JSON.parse() to convert your JSON string to an array. Now that you have an array from you string you can extend the Multi array using Multi.push.apply(Multi, array) as shown below:

var Multi = [];
var test = "[0,1],[1,5],[2,3],[3,10]";
Multi.push.apply(Multi, JSON.parse('[' + test + ']'));

As mentioned in comments, a cleaner approach would be to make sure that your PHP file generates valid JSON. All of this answer would be the same except that you wouldn't need to manually add the square brackets.

like image 50
Andrew Clark Avatar answered Apr 08 '26 19:04

Andrew Clark



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!