1

so in my js function I got an array to which I want to add a dayObject after every for loop. But what happens is that in the end the array consists of the same dayObject. The push() method seems to overwrite every entry. What can I do?

initModel: function (month, year) {
            var days = [];
            var mlength = new Date(year, month, 0).getDate();
            var dayObject = {
                date: null,
                enteredhours: "",
                timefrom: "",
                timeto: "",
                comment: ""
            };

            for (var i = 1; i < mlength; i++) {
                var day = new Date();
                day.setFullYear(year, month, i);
                dayObject.date = day;
                days.push(dayObject);

            }

            return days;

        }
mc_27
  • 23
  • 4

1 Answers1

0

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: ""
        })
    );
}
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392