What causes arrays to unexpectedly change in Angular?

Currently, I am working on a project that involves Angular and Laravel. One interesting issue has arisen in one of my components where I receive a variable from the database as an object array. Surprisingly, even though I only loop through this variable without making any changes to it directly, it seems to update automatically whenever my looping function is called. This behavior has left me puzzled as to the underlying cause. Could it be related to asynchronous operations or perhaps something related to observable subscription?

...
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;
      })
    });
}

The perplexing part is that despite not modifying the 'allOrder' variable directly, it mysteriously changes each time I invoke the 'onAllOrder()' function. Any insights on what could be causing this unexpected behavior would be greatly appreciated.

Answer №1

Although Array.map creates a new array, the objects in both arrays hold the same reference. This means that any changes made to an object in one array will also change the original array.

To avoid this issue, 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;
  })
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Looping through each combination of elements in a Map

I have a Map containing Shape objects with unique IDs assigned as keys. My goal is to loop through every pair of Shapes in the Map, ensuring that each pair is only processed once. While I am aware of options like forEach or for..of for looping, I'm s ...

Protractor end-to-end tests: extracting chosen menu item from page model function

My website has a navigation menu with different items. I'm using a page model for end-to-end tests. In one of my test specs, I need to call a function from the page model that does the following: Check that only one item in the menu has a specific ...

Issue with accessing undefined property in Angular 2+ using Typescript

In my Angular 7 project, I am retrieving data from a service which looks like this: {name: "peter", datetime: 1557996975991} I have a method that is supposed to retrieve this data: myMethod() { this.myService.getdata().subscribe((res) = ...

Using boolean value as default input value in React

When trying to set the default value of a controlled checkbox input from my request, I encountered an error stating "Type 'boolean' is not assignable to type 'string | number | readonly string[] | undefined'". Do you have any suggestion ...

Retrieve the value of a variable to access an object property dynamically in React Native using TypeScript

As I attempted to create dynamic styles for this component, my goal was to determine the styles based on a string passed in as a property. Here is the code snippet: export type MyComponentProps = { styleName: string; } const MyComponent = (props: MyComp ...

Unlock the full potential of the PanelSnap plugin in your angular2 project with these easy steps

I had been successfully using the jquery.Panelsnap plugin on my static HTML pages. However, as I am now transitioning my application to angular8, I am encountering difficulties in referencing the PanelSnap plugin. npm install panelsnap Within my app. ...

Troubleshooting: Angular add/edit form issue with retrieving data from a Span element within an ngFor loop

I am currently working on an add/edit screen that requires submitting a list, among other data. The user will need to check 2-3 checkboxes for this specific data, and the saved record will have multiple options mapped. Here is what the HTML looks like: &l ...

Modifying the dimensions of mat-card in Angular Material

https://i.stack.imgur.com/CP16N.png I am struggling to make both components the same height, similar to the left form. I have tried adjusting margins and padding but nothing seems to work. Below is the HTML code for the parent element: <mat-tab label= ...

Changing the target to a nested component within Angular 4

Within my Angular 4 project, I have a component that is nested inside another. This inner or child component consists of a button, an input field, and a drop-down list. When the button is clicked on the parent page, both the input field and the drop-down ...

Can you explain the rule known as the "next-line" in TypeScript?

No code examples are available for the specific scenario described below: "next-line": [ true, "check-catch", "check-finally", "check-else", "check-open-brace", "check-whitespace" ], ...

Determine the implicit type of the assigned function, while also constraining the return type to be a subtype of a predefined

When writing multiple functions for server requests, I have encountered a dilemma with TypeScript. Each function must return a type that extends a specific predefined known type, but I also want TypeScript to infer the most accurate return type possible. ...

Error: A stream was expected, but you provided 'undefined'. Please provide either an Observable, Promise, Array, or Iterable instead

I'm encountering an error while trying to catch errors in my Ionic-based application with Angular. In the create() method, I am attempting to create a new User. If the username already exists, I receive a response from the backend, but my method thro ...

Ways to set the className prop for all components automatically without having to specify it repeatedly

One challenge I face is dealing with code duplication whenever I create a new component. Is there a way to pass the className property between components without having to explicitly define it every time a new component is created? For example, when I cr ...

Utilizing the axios create method: troubleshooting and best practices

I am attempting to use the axios library in my Next.js app (written in TypeScript) to access a public API for retrieving IP addresses from . In my index.ts file, I have the following code: import axios from "axios"; export const ipApi = axios.cr ...

Angular2 Animation for basic hover effect, no need for any state change

Can anyone assist me with ng2 animate? I am looking to create a simple hover effect based on the code snippet below: @Component({ selector: 'category', template : require('./category.component.html'), styleUrls: ['./ca ...

Isolating the Root Module in Angular 2

There are two main pages in my website: Index.html (Home Page) Admin.html (Admin Control Panel which requires sign-in to access) Do I need to create a separate root module for each page, or can they be bundled together using webpack in a single root mod ...

Sign up for a service that sends out numerous simultaneous requests for every item in a list

I am encountering an issue with my Angular 5 component that is responsible for displaying a list of items. The items are fetched from a service and populated in the component by subscribing to the service. The service first makes a request to retrieve the ...

Choose a dynamic ngFor item attribute to be placed as a property in the @Input decorator

In my Angular 6 code, I am attempting to create a select component. <ng-select [(ngModel)]="selecteditemid"> <ng-option *ngFor="let item of items" [value]="item.id"> {{item.inputfield}} <---- ERROR </ng-option> </ng-se ...

Unable to render image despite being located in the identical directory

I'm currently working on an Angular component and facing some issues with displaying an image. I've tried hardcoding the img src for now, but eventually, I want to implement it dynamically. Both my component and the image files are located in th ...

The property of the Angular Typescript object is distinctly not defined, yet the property itself is

Currently facing a bizarre issue. Even though the console displays data in an object from a subscribed observable, TypeScript code shows it as undefined. Take a look: initData(): void { this.backendService.getData().subscribe((depotDays: DepotDayAcc ...