0

I am pushing elements into array, and the problem is that each time I push a new element, all the previous elements become equal to the last one. I have come across this post, but I still can't see how to fix the issue

Please see this jsFiddle. As the post suggests, I moved the declaration of instance to the for-loop, but I've still got the same problem. Namely, the output of the code looks like this: [46, 46]. However, I would expect it to be [23, 46].

I am really going crazy. Any ideas???

$(document).ready(function() {
  var json = {'name': 'Anna', 'counter': 1}
  var counters = [23, 46];
  var result = [];
  $(counters).each(function() {
    
      var instance = json;
      instance.counter = this;
      result.push(instance);
  });
  
  $(result).each(function(){
      $('#test').append('<li>' + this.counter + '</li>');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id = 'test'>

</ul>
Edgar Navasardyan
  • 4,261
  • 8
  • 58
  • 121

2 Answers2

1

You should do deep copy using var instance = jQuery.extend(true,{},json);

$(document).ready(function() {
  var json = {'name': 'Anna', 'counter': 1}
  var counters = [23, 46];
  var result = [];
  $(counters).each(function() {
    
      var instance = jQuery.extend(true,{},json);
      instance.counter = this;
      result.push(instance);
  });
  
  $(result).each(function(){
      $('#test').append('<li>' + this.counter + '</li>');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id = 'test'>

</ul>
karthik reddy
  • 479
  • 4
  • 12
0

You could move the object inside of the each function and create for every call a new reference, without using the same reference to the object.

$(document).ready(function() {
  var counters = [23, 46];
  var result = [];
  $(counters).each(function() {
      var instance = { name: 'Anna', counter: 1 };
      instance.counter = this;
      result.push(instance);
  });
  
  $(result).each(function(){
      $('#test').append('<li>' + this.counter + '</li>');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id = 'test'></ul>

As alternative, you could create a new object with Object.create

$(document).ready(function() {
  var json = {'name': 'Anna', 'counter': 1}
  var counters = [23, 46];
  var result = [];
  $(counters).each(function() {
      var instance = Object.create(json);
      instance.counter = this;
      result.push(instance);
  });
  
  $(result).each(function(){
      $('#test').append('<li>' + this.counter + '</li>');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id = 'test'></ul>
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392