Miguel Frias
Miguel Frias

Reputation: 2710

Loop return always the same last value

im create a loop to create objects.

Action.ts

public campaing:any = {
    'id': '',
    'campaing_code': '',
    'campaing_type': '',
    'start_date': this.currentDate,
    'end_date': this.currentDate,
    'deadline': this.currentDate,
    'creation_date': this.currentDate,
    'special': false,
    'os': '',
    'country': '',
    'campaing_country': 'germany',
    'version_app': '',
    'permanent_promo': false,
    'promo_tag': 'ABS-W-',
    'editor_name': '',
    'plus_promotag': '',
    'status': 'Successful',
    'application': {},
    'publisher': {},
    'contact': '',
    'sended': false
  };
  public searchparram: any = {
    'type': '',
    'time': '',
    'start_date': this.currentDate,
    'deadline': this.currentDate,
    'publisher': {},
    'wildcard': false,
    'os': '',
    'category': '',
    'number_campaings': 1
  }
public suggescampaings:any = [];      
public generateCampaings(){
        this.campaing.campaing_code = this.searchparram.type;
        this.campaing.start_date = this.searchparram.start_date;
        this.campaing.deadline = this.searchparram.deadline;
        this.campaing.publisher = this.searchparram.publisher;
        this.campaing.os = this.searchparram.os;
        for (let i = 1; i <= this.searchparram.number_campaings; i++) {
          ((i)=>{
            this.campaing.id = i; /* Here should print i but alway print the last value of i */
            this.suggescampaings.push(this.campaing);
          })(i);
        }
      }

But when i try to put the camaping.id = i, always return the last value of the iteration. i mean if the iteraion is 8 times always give as id 8.

So the idea is to put as id the iteration and then push in to the array the object.

Upvotes: 1

Views: 1098

Answers (2)

Saravana
Saravana

Reputation: 40712

The issue is that you are modifying the same this.campaing object in each loop. If you intended to push a new object for each loop, you can easily create a copy by using Object.assign:

for (let i = 1; i <= this.searchparram.number_campaings; i++) {
  ((i) => {
    let copy = Object.assign({}, this.campaing);
    copy.id = i;
    this.suggescampaings.push(copy);
  })(i);
}

Upvotes: 1

Amit Chigadani
Amit Chigadani

Reputation: 29795

Problem is not with the loop, It is because you have not created new object before pushing the object into an array suggescampaings. The same object campaing is getting overwritten multiple times, and if you display the array it is going to display the same object (i.e last object) multiple times.

Suggestion : Create new temporary object every time inside the loop then push it into an array.

Upvotes: 0

Related Questions