Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript push with complex objects

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

like image 455
ema Avatar asked May 22 '26 13:05

ema


1 Answers

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

like image 117
fyr Avatar answered May 24 '26 01:05

fyr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!