Array Push Is Overwriting the Existing Array

Push is overwriting previous data in array

Calling push will not copy your object, because JavaScript Objects are passed by reference: you're pushing the same Object as every array entry.

You can fix this easily by moving the var UserDataEntry = {}; inside the loop body, so that a new object is created each loop iteration:

    for (var x = 0; x < (tempUserData.length); x++) {
var UserDataEntry = {};

Push() overwrites existing objects in an array

You could take a copy of the object for pushing. This avoids the same object reference.

days.push({ ...dayObject });

Or map a new array.

initModel: function (month, year) {
const getDate = day => {
const date = new Date();
date.setFullYear(year, month, day);
return date;
};
return Array.from(
{ length: new Date(year, month, 0).getDate() },
(_, i) => ({
date: getDate(i + 1),
enteredhours: "",
timefrom: "",
timeto: "",
comment: ""
})
);
}

Array push overwrite all records of an array

There is no csvRecord defined anywhere in your code, so I assume, you are actually pushing headerRecord to the array?

If that's the case, the answer is obvious. You are always assigning

headerRecord = this.headersRowData;

which does not create a new object but just assigns headerRecord to be an additional reference to this.headerRowData. Thus, they are both pointing to the same memory location. When you then do

csvArr.push(headerRecord);  //I assume this should be headerRecord

you are just adding an additional reference to the very same object to the array. Ie all elements of the array are in fact pointing to the very same location in memory.
In the loops body you are then updating the headerRecord object. And with this update, you are of course also updating all other references, that are pointing to this object. Thus, it seems, it's overwriting many elements. But in reality, it's just changing one element, but all other elements are also pointing to that very same element and therefore reflect these changes as well.

So instead of

let headerRecord: {};
headerRecord = this.headersRowData

just do

let headerRecord = {};
//remove the assignment to this.headerRowData

// update the object here

csvArr.push(headerRecord);

This will create and add a new object in every iteration, which is not related to the other objects ...

PHP array_push() is overwriting existing array elements

It's because when you use:

array_push($myObjArray->message_recipients, $myRecipientsObj);

you are pushing a reference to the object into the array, and when you then change the object in subsequent passes through the loop, you effectively change the contents of each element of the array. To work around this, you need to push a copy of the object into the array instead:

array_push($myObjArray->message_recipients, clone $myRecipientsObj);

Demo on 3v4l.org

JS array.push keeps overwriting

This line here:

let tempDesign = design,

will create a reference to the variable design. (In case you don't know what a reference is, think of it as an alternative name to an existing variable). Later, after you modify the contents of tempDesign, you push it to the array. The new array element holds a reference to design.

Now, if we look at the next (possible) iteration of your for-loop, the new variable tempDesign is another reference to the same variable design, which is already referred to by the 1st element in the array x, and that is pushed to the array! And so, every next iteration of your for-loop pushes another, duplicate reference to the array x, all of which refer to the same variable design.

The fix is to make a copy of the variable design to avoid creating the showcased reference "maze". There are multiple methods of cloning objects in JavaScript, but this simple yet effective method should do the trick in your use case:

let tempDesign = JSON.parse(JSON.stringify(design));

This will make a new variable tempDesign, which is an object on its own, and thus isn't a reference to design anymore, while holding all data originally contained in design.

.push() overwrites array values in Javascript

I figured it out. Here's the answer.

// When you push an array or array element to another array,
// you don't copy the *data* to the new array;
// you copy a *reference* to the original array or array element.
// If you change the elements of the original array,
// the elements you pushed also change.

main = [];
sub = [1,2,3];
main.push(sub); // main now contains 1,2,3 as a *reference* to the sub
sub[0]=9;
alert(main); // Contains 9,2,3

//------------------------------------------------------------------------------------
// Redefining the original array destroys the link/reference.
//------------------------------------------------------------------------------------
main = [];
sub = [1,2,3];
main.push(sub); // main now contains 1,2,3 as a *reference* to sub
sub = []; // sub has been redefined, destroying the link.
sub[0]=9;
alert(main); // Contains 1,2,3

//------------------------------------------------------------------------------------
// Setting the values for a whole array redefines it, destroying the links.
//------------------------------------------------------------------------------------
main = []; // Redefines the array, destroying links
main = [4,5,6]; // Providing initial values redefines the array, too
// (destroying links).

//------------------------------------------------------------------------------------
// Changing the value of an element is *not* a redefinition of the array,
// so links persist.
//------------------------------------------------------------------------------------
main = [];
sub = [1,2,3];
main.push(sub); // main now contains 1,2,3 as a *reference* to sub
sub[0]=9; // Does not redefine main, only changes one of its element. Refs remain intact.
alert(main); // Contains 9,2,3

Array.Push overwrites the previous Value Node Js

Problem:

You problem is when you assign the value to eachUserId to object data. You have only 1 object named data and you are adding this same object into the array over and over again. But remember they all refer to the same object, and when you'll change anything in that object it'll reflect everywhere.

So, when you change data.eachUserId = key; in loop, it changes for all items in array. And at the end all of them contains the last eachUserId value you assigned to it.

Solution:

You need to clone the object, and then push it into the array.


I will suggest you to use lodash library and cloneDeep method to create a deep clone of your object.

var _ = require('lodash');  //require "lodash"

socket.on('commentAdded', function (data) {
if (data !== null) {
Object.keys(users).forEach(function (key) {
if (key !== "null") {
var dataClone = _.cloneDeep(data); //create deep clone
dataClone.eachUserId = key; //assign "key"
comments.push(dataClone); //push into the array
}
});
console.log("comment was added");
}
socket.broadcast.emit('onCommentAdded', data);
});

Pushing to Array Overwrites Similar Entries

The problem is that you are not pushing copies of the objects to the array cliAllow, but you're pushing references to the same object(s).

So let's go through the first iteration of the outer while loop to see what the result is:

cliAllow.push(arr[4]);
cliAllow.push(arr[4]);
cliAllow.push(arr[4]);

Now, cliAllow.length is 3, with indexes from 0 to 2, but you have 3 array items pointing to the very same object (the last one in the notPassed array, since you're counting backwards.)

So, cliAllow[0], cliAllow[1], cliAllow[2] all now references the same object.

That means, when you're setting the party property, you're change the same object 3 times:

cliAllow[2].party = "NT";
cliAllow[1].party = "VL";
cliAllow[0].party = "LF";

You're essentially doing this:

var obj = {milestone: "Mlstn4", client: "Client2", trade: "Trade3", units: "25.0", party: "B"};

obj.party = "NT";
obj.party = "VL";
obj.party = "LF";

As you can see, you're writing to the same property on the same object 3 times here, which means it will be set to the last value you give it ("LF" in this case).

In your code, you have 5 items in the notPassed array, but instead of 15 different objects, you have only 5, and each one of those 5 objects gets its party property set to the last value in the mlstnParties array.

One way of solving this is to make a copy function:

function copy(obj) {
var cp = {};
for (var o in obj) {
cp[o] = obj[o];
}
return cp;
}

See it in action here: http://jsbin.com/kibeba/2/edit



Related Topics



Leave a reply



Submit