0

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.

4
  • 1
    use forEach for array looping, not map Commented May 15, 2020 at 1:01
  • what kind of changes ?? unexpected changes in the object or length ..? Commented May 15, 2020 at 2:45
  • is best to use key let instead of var, (scooped variable) Commented May 15, 2020 at 2:46
  • Changes happen in the num option of allOrder arrary. groupItem.num = groupItem.num + itemAll.num; Commented May 15, 2020 at 3:12

1 Answer 1

2

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;
  })
});
Sign up to request clarification or add additional context in comments.

1 Comment

I used forEach method but still changes the array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.