I have a small calendar application. For that there is an array, dates, as follows:
const dates = [Thu Oct 01 2020 00:00:00 GMT+0400 (Azerbaijan Standard Time),
Thu Oct 08 2020 00:00:00 GMT+0400 (Azerbaijan Standard Time),
Thu Oct 15 2020 00:00:00 GMT+0400 (Azerbaijan Standard Time),
Thu Oct 22 2020 00:00:00 GMT+0400 (Azerbaijan Standard Time),
Thu Oct 29 2020 00:00:00 GMT+0400 (Azerbaijan Standard Time),
Thu Nov 05 2020 00:00:00 GMT+0400 (Azerbaijan Standard Time)]
Not I am iterating over dates using the forEach loop and on each iteration setting the value to an object and pushing that object in another array. The is the code below. It is the code inside a class based component of React and hence data is being accessed using this.data
data = {};
dataArray = [];
dates.forEach((date) => {
this.data.slots = values; //some other data from code
this.data.date = moment(date).toDate();
this.dataArray.push(this.data);
console.log(this.dataArray);
});
However I fail to understand the output in console when I console the value of dataArray. It shows the correct value initially but after expanding it, it shows the value of date from the last iteration.Ss attached below.
The screenshot is the console value of a single iteration when date is equal to Thurs Nov 5 2020.However the case is the same for every iteration. It shows correct value written and upon expanding gives the last array value in date.
And then of course the whole dataArray has objects with date equal to 5 Nov at every index. Why is this happening?
