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?
1 Answer 1
This is much safer and readable
function formToArray(frm){
var AllAnnotationsQuestion=[];
for (var i = 0; i < frm.length; i++) {
AllAnnotationsQuestion.push({
'AnnotationsQuestion': {
'question_id': frm[i].name.substring(13),
'answer': frm[i].value,
'id':0
}
});
}
return AllAnnotationsQuestion;
}
answered Jan 5, 2013 at 16:53
mplungjan
180k29 gold badges183 silver badges246 bronze badges
Explore related questions
See similar questions with these tags.
lang-js
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.