Ajax Response Conversion
I have this array that is returned by ajax: console.log(res); ['07Apr|1', '06Apr|3', '05Apr|12', '04Apr|11', '03Apr|0', '02Apr|0', '01Apr|6', '31Mar|0', '30Mar|7', '29Mar|16', '28M
Solution 1:
You can parse the data you received from the ajax response to create the array.
var populateArray = function (ajaxResponse) {
var newArray = [];
ajaxResponse.forEach(function (item, index) {
var props = item.split('|');
var obj = {
date: props[0],
downloads: props[1]
};
newArray.push(obj)
});
return newArray;
}
To demonstrate, try
console.log(populateArray(["07Apr|1", "06Apr|3", "05Apr|12", "04Apr|11", "03Apr|0", "02Apr|0", "01Apr|6", "31Mar|0", "30Mar|7", "29Mar|16", "28Mar|5", "27Mar|5", "26Mar|12", "25Mar|9", "24Mar|4", "23Mar|10", "22Mar|16", "21Mar|2", "20Mar|19", "19Mar|22", "18Mar|10", "17Mar|11", "16Mar|10", "15Mar|19", "14Mar|0", "13Mar|4", "12Mar|14", "11Mar|5", "10Mar|26", "09Mar|7", "08Mar|5"]));
Solution 2:
Stringify the entire structure when it is ready, not segments.
Don't use eval ever, use JSON.parse() instead.
var obj = [];
var daysBack = 30;
var objItem = {};
for(var x = 0; x <= daysBack; x++){
var currObj = res[x];
var objCombo = currObj.split("|");
var objItem = {date: objCombo[0], downloads: objCombo[1]};
//objItem = JSON.stringify(eval("(" + objItem + ")"));
obj.push(objItem);
}
obj = JSON.stringify(obj);
Post a Comment for "Ajax Response Conversion"