1

I have the following code. Essentially what I do is I have a loop, and within the loop I have logic that creates a few values. I want to insert those values into an Object, and then insert that Object into an Array.

Now in each iteration, the object values change, so in case this loop runs 2 times, I'd expect to have two different objects.

Problem is, on first iteration, I push a distinctive object into an array, and then on the 2nd iteration, I have a new object with different values, but after I do .push - it overwrites my earlier entry with the new values, and insert a new object into the array.

I.E. I end up have 2 identical objects in the array. What is happening?

  var arr = [];
  var filObj={};

  for (var i = 0; i<3; i++){ //looping
  
      //I do some logic and derive a few fields and insert them into my `filObj`

      filObj['col1'] = 'Hello';
      filObj['col2'] = 'Yellow';
      filObj['col3'] = 'Seven';

      arr.push(filObj); 

  }
JaRule1986
  • 85
  • 5
  • also [How to push object to array from for loop properly in JavaScript?](https://stackoverflow.com/questions/36602160/how-to-push-object-to-array-from-for-loop-properly-in-javascript) – pilchard Feb 14 '23 at 23:43
  • @pilchard - my bad, I did not notice this question – JaRule1986 Feb 15 '23 at 14:03

1 Answers1

1

You are inserting the same object in each iteration. The fix is to a create a new object every time.

  var arr = [];

  for (var i = 0; i<3; i++){ //looping
      var filObj={};
  
      //I do some logic and derive a few fields and insert them into my `filObj`

      filObj['col1'] = 'Hello';
      filObj['col2'] = 'Yellow';
      filObj['col3'] = 'Seven';

      arr.push(filObj); 

  }
Anton Podolsky
  • 841
  • 2
  • 11
  • There are a number of ways to 'fix' it. Take the time to explain that objects are passed by reference in javascript and the side effects of that. (but actually flag to close as duplicate). – pilchard Feb 14 '23 at 23:44