1

I have an ajax call which returns an array of strings and I need to convert this array into a javascript array : I explain with examples :

my return from ajax call is like that :

 success: function (doc) {

doc.d[0] // =  "{ 'title': 'Espagne', 'start': '2016-05-24', 'end': '2016-05-25' }" 
doc.d[1] // = "{ 'title': 'Italie', 'start': '2016-05-18', 'end': '2016-05-20' }"
....

And I want to create a JavaScript Array like that :

 var countries = new Array();
 countries[0] = { 'title': 'Espagne', 'start': '2016-05-24', 'end': '2016-05-25' };
 countries[1] = { 'title': 'Italie', 'start': '2016-05-18', 'end': '2016-05-20' };

Have you an idea how to take the return string from doc.d and convert it to an array ?

If i do a thing like that :

var countries = new Array();
coutries[0] = doc.d[0] 

it can't work

It is possible to use .map() or .push() to build a new array using doc.d ?

2
  • 1
    if you get a JSON conform string, you could use JSON.parse(). Commented May 26, 2016 at 10:20
  • 1
    It works ! But i have to add in my case : JSON.parse('['+doc.d+']') Commented May 26, 2016 at 12:08

3 Answers 3

2

Just simply assign list to another variable

Try like this

var countries  = JSON.parse(doc.d);
Sign up to request clarification or add additional context in comments.

1 Comment

This way countries will have values as string, not in object format.
2

The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.

JSON.parse(doc.d[0]);

Comments

0

Try following code

doc.d[0] =  "{ 'title': 'Espagne', 'start': '2016-05-24', 'end': '2016-05-25' }" 
doc.d[1] = "{ 'title': 'Italie', 'start': '2016-05-18', 'end': '2016-05-20' }"

var arr = [];
if(doc.d.length)
{

    for(var i in doc.d)
    {
        arr.push(JSON.parse(doc.d[i]));
    }

    console.log(arr);
}

Else

doc.d[0] =  "{ 'title': 'Espagne', 'start': '2016-05-24', 'end': '2016-05-25' }" 
doc.d[1] = "{ 'title': 'Italie', 'start': '2016-05-18', 'end': '2016-05-20' }"

var arr = [];
if(doc.d.length)
{

    for(var i in doc.d)
    {
        arr.push(doc.d[i].split('"')[1]); //This way also you can do
    }

    console.log(arr);
}

So arr[0] will be same as object of doc.d[0] and so on.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.