3

I'm building an array of objects which have a property of type array:

here's some simplified code:

var _data = [];
for(var i=0;i<10;i++) {
  var element = {
        id: i,
        answers: []
  };

  for(var j=0;j<3;j++) {                        
    var answer = {
      id: j,
      description: ''
    };
   element.answers.push(answer);
  }
  _data.push(element);
}

At the end of the two cicle the array _data has 10 elements but each element has the property answer empty (I expect 3 items for each element). Why this happens? It seems like the push doesn't push the entire object but only the "first level properties". thanks

1
  • Your code works for me, are you sure it isn't a display issue? Try checking the output of _data.toSource(). Commented Dec 21, 2011 at 14:56

1 Answer 1

1

Running your code in Firefox 8 results in the following _data array:

_data:

[{id:0, answers:[{id:0, description:""}, {id:1, description:""}, {id:2, description:""}]}, 
 {id:1, answers:[{id:0, description:""}, {id:1, description:""}, {id:2, description:""}]}, 
 {id:2, answers:[{id:0, description:""}, {id:1, description:""}, {id:2, description:""}]}, 
 {id:3, answers:[{id:0, description:""}, {id:1, description:""}, {id:2, description:""}]}, 
 {id:4, answers:[{id:0, description:""}, {id:1, description:""}, {id:2, description:""}]}, 
 {id:5, answers:[{id:0, description:""}, {id:1, description:""}, {id:2, description:""}]}, 
 {id:6, answers:[{id:0, description:""}, {id:1, description:""}, {id:2, description:""}]}, 
 {id:7, answers:[{id:0, description:""}, {id:1, description:""}, {id:2, description:""}]}, 
 {id:8, answers:[{id:0, description:""}, {id:1, description:""}, {id:2, description:""}]}, 
 {id:9, answers:[{id:0, description:""}, {id:1, description:""}, {id:2, description:""}]}]

Maybe you have a typo because it is answers not answer

Sign up to request clarification or add additional context in comments.

Comments

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.