Li Gang
Li Gang

Reputation: 49

Why array unexpectedly changes in Angular

I am working on Angular+laravel project. In one component I received one variable from database which is object array. I do not change it just looping through that variable but it changes automatically whenever the function looping called. I am not sure why it works. Is it related with Async or observable subscribe?

...
allOrder: { date_time: Date,tableID: string, identity: string, paid:boolean, orders: Order[]}[] = [];

...
constructor(private basicService: BasicService) { 
    this.getOrder();
}
...
getOrder(): void {
   this.basicService.getOrders().subscribe(items => {
      items.map(item => {
          this.allOrder.push(item); 
        }
      })
  })
}
...
onAllOrder() {
    var displayAllOrder = [];
    var displayNum = 0; 
    this.allOrder.map(itemsAll => {
      itemsAll.orders.map(itemAll => {
        displayAllOrder.map(groupItem => {
          if(groupItem.productID == itemAll.productID){
            groupItem.num = groupItem.num + itemAll.num;
            displayNum = 1;
          }
        })
        if(displayNum == 0) displayAllOrder.push(itemAll);
        displayNum = 0;
      })
    });
}

I do not change variable allOrder but it changes whenever I call onAllOrder function. Please help me.

Upvotes: 0

Views: 129

Answers (1)

Akhil Chandran
Akhil Chandran

Reputation: 460

All though Array.map creates new array, the objects in former and latter holds the same reference. So, any changes to the object will change the original array.

Here, you can use forEach instead.

this.allOrder.forEach(itemsAll => {
  itemsAll.orders.forEach(itemAll => {
    displayAllOrder.forEach(groupItem => {
      if(groupItem.productID == itemAll.productID){
        groupItem.num = groupItem.num + itemAll.num;
        displayNum = 1;
      }
    })
    if(displayNum == 0) displayAllOrder.push(itemAll);
    displayNum = 0;
  })
});

Upvotes: 2

Related Questions