I’m trying to loop through a pipe delimited list passed to a function, split it out into an array based on the pipe as a separator, and then break each item out into its component parts, where the format is as follows:
“76:1167|76:1168”
so that the array would be: surveyQuestions[0] = 76:1167. And then that would be split up into : surveyQuestions[0].question = 76 and surveyQuestions[0].answer = 1167.
And this is the code I’m using, but the values come back undefined when I try to add the properties to each array item.
function answerSurvey(survey){
var surveyResults = survey.split("|");
for (var i=0;i<surveyResults.length;i++){
var surveyResult = surveyResults[i].split(":");
var surveyQ = surveyResult[0];
var surveyA = surveyResult[1];
surveyResults[i].surveyQ = surveyQ;
surveyResults[i].surveyA = surveyA;
console.log(surveyResults[i].surveyQ + "|" + surveyResults[i].surveyA)
}
}
answerSurvey("76:1167|76:1168");
You are trying to add a property to a string, which you cannot do. If you want the Array to contain a list of Objects, use
Array.map()to transform your strings into objects:It is included in most browsers, but for older versions of some browsers, you’ll need to add
.map()manually.Edit: jQuery does add a map function (as noted in the comments). Tweak the code above slightly to include the array as the first parameter to
$.map()and substitute the argument name forthis(or shift theresultargument one to the right, followingindex):