I have a problem when inserting an array into another array in this loop:
function formToArray(frm){
var sAux={};
var AnnotationsQuestion={};
var AllAnnotationsQuestion=[];
for (i = 0; i < frm.length; i++) {
//next line dont work
sAux['question_id'] = frm[i].name.substring(13)
sAux['answer']=frm[i].value;
sAux['id']=0;
AnnotationsQuestion['AnnotationsQuestion']=sAux;
AllAnnotationsQuestion.push(AnnotationsQuestion);
}
return AllAnnotationsQuestion
}
this returns the first result repeated x times
example of a return value
[{'AnnotationsQuestion':{'question_id':4,'answer':
'AA'....}},{'AnnotationsQuestion':{'question_id':4,'answer':
'AA'....}}]
what is the problem of this loop?
AllAnnotationsQuestionon each iteration, rather a reference to the same object. Therefore, all elements of the returned array have the same value. If you dovar sAux = {}at the beginning of yourforloop, it should create a new object for that iteration, and then you will get unique values.var sAux = {};and notSaux var = {};... Anyway, look at the answer by @mplungjan, it's much cleaner.AnnotationsQuestionas well. Once again, what you're pushing is a reference to a single object. Naturally, values are same across the board. You would have to dovar AnnotationsQuestion = {};at the beginning of each iteration, along withvar sAux = {};. Check jsfiddle.net/rtSYC/3.