Search code examples
arraysangulartypescriptangular-reactive-formsangular-forms

Angular 5 - Creating array of objects from FormGroup pushes the same object into my array


I believe I'm having trouble with javascript/typescript pass by reference.

I have an array of objects that I need to create from a FormGroup. All FormGroup attributes should stay the same for each object, except for the ObjectDate. So I loop through my array but I end up pushing the same object into my array.

for (let i = 0; i < this.objects.length; i++) {

    const object = this.fg.value as Object;

    object.ObjectDate = new Date(this.date.getDate() + i);

    this.objects.push(object);
}

The resulting array has objects that all have the same ObjectDate. For example, if today is August 30, all of the objects in the array have an ObjectDate of September 6.


Solution

  • Your main issue is the line:

    const object = this.fg.value as Object;
    

    Every iteration you're modifying the same object. To create a copy of this.fg.value you can use Object.assign:

    Object.assign({}, this.fg.value)
    

    Object.assign copies all of the properties from the object passed as the second parameter into the object passed as the first parameter.

    Another big issue is the line:

    object.ObjectDate = new Date(this.date.getDate() + i);
    

    When you pass a number into the constructor new Date(value) the values is taken as the number of milliseconds since January 1, 1970, 00:00:00 UTC. So each iteration only goes up by 1 millisecond not day.

    You could resolve this issue by using setDate instead, for example:

    // Create a copy of the re-used date
    object.ObjectDate = new Date(this.date.getTime());
    // Increment the date for each iteration
    object.ObjectDate.setDate(this.date.getDate() + i);
    

    Another troubling line

    this.objects.push(object);
    

    You're adding objects to the array that you're iterating over. Maybe you meant to do

    this.objects[i] = object;
    

    Welcome to Stack Overflow, best of luck in your learning!