Push Is Overwriting Previous Data in 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: ""
})
);
}

Javascript push Object to global array overwrites previous values?

You could try to declare and instantiate the mark object inside the for loop because right now you are modifying the same instance all the time:

function getCoordinates() {
for(var key in _data) {
var mark = {};
if(_data.hasOwnProperty(key)) {
mark["lng"] = _data[key].long;
mark["lat"] = _data[key].lat;
}
_coordinates.push(mark);
}

console.log(_coordinates);
}

Array OverWrite itself by pushing Objects (JavaScript)

Relevant: Push is overwriting previous data in array

Every iteration of the loop, what you're doing is changing the properties of a single object aObj and pushing it to arrS.

Instead, you should be creating a new object for each iteration by pulling var aObj={} inside the loop.

make an array.push inside a map is getting overwriting previous data (reactJs)

You should not use .map for side-effects. You are iterating moviesId.arr array and then for each element pushing moviesId.arr.length number of data.poster_path values into array a. This is where your duplicates are coming from.

I suggest loading up the ApiMovieList(item) calls in an array of Promises and use Promise.all to wait for all of them to resolve. You'll then have a resolved array of poster paths to set to UserDataEntry and log.

useEffect(() => {
// the Array A in the question
const posterReqs = moviesId.arr.map(item => {
return ApiMovieList(item).then(data => data.poster_path);
});

Promise.all(posterReqs).then(posters => {
// the Array B in the question
const UserDataEntry = posters || [];
console.log(UserDataEntry);
});
});

.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 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 ...

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);
});

javascript .push overwrites previous array values by duplicating the new values

Simply create a new local array before pushing the same one (the same reference) each time:

    $scope.getData = function() {
$scope.series.length = 0
$scope.allData.length = 0

var dateArray = ["2015-04-03 00:00:00", "2015-04-04 00:00:00", "2015-04-05 00:00:00", "2015-04-06 00:00:00", "2015-04-07 00:00:00"]

for (var i = 0 ; i < $scope.dataDisplayModel.length ; i++) {
var dataArray = []; // create a new local var each iteration
if ($scope.dataDisplayModel[i].checked === true) {
var field = $scope.dataList.fields.indexOf($scope.dataDisplayModel[i].field);

// dataArray.length = 0; // this will not clear the array!!!!

for (var j = 0 ; j < 5 ; j++) {
var arrayList = $filter('filter')($scope.dataList.values, dateArray[j], true);
var sum = _.sum(arrayList, field);
dataArray.push(sum);
}
$scope.allData.push(dataArray);
}
}
}


Related Topics



Leave a reply



Submit