Reputation: 716
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 ?
Upvotes: 1
Views: 83
Reputation: 355
The JSON.parse()
method parses a JSON string, constructing the JavaScript value or object described by the string.
JSON.parse(doc.d[0]);
Upvotes: 2
Reputation: 25352
Just simply assign list to another variable
Try like this
var countries = JSON.parse(doc.d);
Upvotes: 2
Reputation: 2766
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.
Upvotes: 0