0

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?

8
  • You are not pushing a new object to AllAnnotationsQuestion on each iteration, rather a reference to the same object. Therefore, all elements of the returned array have the same value. If you do var sAux = {} at the beginning of your for loop, it should create a new object for that iteration, and then you will get unique values. Commented Jan 5, 2013 at 16:49
  • Yes, I also thought the same but putting Saux var = {}, at the beginning of each iteration, I got the same result Commented Jan 5, 2013 at 16:55
  • I do hope it was var sAux = {}; and not Saux var = {};... Anyway, look at the answer by @mplungjan, it's much cleaner. Commented Jan 5, 2013 at 16:58
  • yes it is var sAux = {}; im sorry. Commented Jan 5, 2013 at 17:06
  • 2
    I see. Yes, I'm sorry. The same object argument goes for AnnotationsQuestion as 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 do var AnnotationsQuestion = {}; at the beginning of each iteration, along with var sAux = {};. Check jsfiddle.net/rtSYC/3. Commented Jan 5, 2013 at 17:16

1 Answer 1

2

This is much safer and readable

DEMO

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; 
}
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the answer, but I got this error with your solution 'Uncaught SyntaxError: Unexpected token : '
This error is the chrome browser, in this line 'AnnotationsQuestion': {

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.