Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize Array with string in array form

I have a string which is got from ajax result:

["name1", "name2", "name3", "name4", "name5"]

The string pattern is exactly as above, including ", and the total element is not fixed

I tried below code but doesn't work:

var strArr="";
$.ajax({url:"myurl",success:function(result){
     strArr=result;
}});
var arr = new Array(strArr);

Update: This is my latest code

var strArr="";
$.ajax({url:"myurl",success:function(result){
    strArr=result;
    alert(strArr); //["name1", "name2", "name3", "name4", "name5"]
}});
var arr= JSON.parse(strArr);
like image 834
DnR Avatar asked Aug 24 '26 05:08

DnR


1 Answers

To convert that string to an actual Array, just do JSON.parse, like this

var data = '["name1", "name2", "name3", "name4", "name5"]';
console.log(JSON.parse(data));
# [ 'name1', 'name2', 'name3', 'name4', 'name5' ]

You can confirm the type of object returned, like this

console.log(Object.prototype.toString.call(JSON.parse(data)));
# [object Array]

Your actual code, should look something like this

$.ajax({
    url: "myurl",
    success: function(result) {
        alert(JSON.parse(result));
    }
});
like image 109
thefourtheye Avatar answered Aug 25 '26 20:08

thefourtheye



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!