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 ?
-
1if you get a JSON conform string, you could use JSON.parse().Nina Scholz– Nina Scholz2016年05月26日 10:20:51 +00:00Commented May 26, 2016 at 10:20
-
1It works ! But i have to add in my case : JSON.parse('['+doc.d+']')Julien698– Julien6982016年05月26日 12:08:45 +00:00Commented May 26, 2016 at 12:08
3 Answers 3
Just simply assign list to another variable
Try like this
var countries = JSON.parse(doc.d);
1 Comment
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.
JSON.parse(doc.d[0]);
Comments
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.