Click here to Skip to main content
15,891,253 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
My array of objects being assigned values in document ready -> div load gets overwritten with the last value. Each object in the array is same (last one).

What I have tried:

I have this array of objects being loaded:

<pre>$(document).ready(function () {
  $("<div></div>").load("/Stats/Contents #stats", function () {
    statcount = $(".list-group-item", this).length;

    for (var j = 0; j < statcount; j++) {
      statList.push(stat);
    }

    for (var i = 0; i < statcount; i++) {
      statList[i].statId = document.getElementById("statId-" + (i + 1) + "").value;
      statList[i].productDescription = document.getElementById("productType-" + (i + 1) + "").value;
      statList[i].lastMeasuredInventoryAmount = document.getElementById("statLastMeasureAmount-" + (i + 1) + "").value;
    }
  )}
)}

..and so on. Then I get the changed values and save them, however, in the ajax post call, all of the array objects are same (the last one assigned), looks like they get overwritten. Any ideas? I saw these deferred/promise type code but not sure if there's simpler way. Thanks.
Posted
Updated 10-Aug-17 9:03am
Comments
Kornfeld Eliyahu Peter 10-Aug-17 13:44pm    
Have you debug it?

1 solution

Quote:
JavaScript
statList.push(stat);

You haven't shown us where you create it, but it looks like you're pushing the same object into the array in a loop. Any update to a property of that single object will then be reflected no matter which array index you access it from.

You need to create a new object for each slot in the array.
JavaScript
for (var j = 0; j < statcount; j++) {
    var stat = {};
    statList.push(stat);
}
 
Share this answer
 
Comments
Ekjon 10-Aug-17 15:20pm    
Hi Peter, Sorry I pasted an older version of the code. I did in fact change it to have a new object every time like you suggested. e.g.
for (var i = 0; i < statcount; i++) {      
         var statCopy = stat;      
         statCopy.statId = document.getElementById("statId-" + (i + 1) + "").value;      
         ......      
         statList.push(statCopy);
}


But it did not make a difference. Debugging shows the loop correctly assigns values to the array of objects. However, when I try to do the post in another click method, now the array contains all the same values for each slot.
Richard Deeming 14-Aug-17 5:32am    
You're still putting the same object in each slot in the array. Making a new variable to point to the object doesn't make a copy of the object.

Use: var statCopy = {}; to make a new object.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900