0

I need some help please. I have a simple Angular app that takes some form input values. These values get passed to a simple method, where the values are assigned to the matching property values of an object. Finally this object is pushed into an array.

My problem is this; every time the values passed into the method are assigned to the my object's property values, all other objects' (already in my array) properties gets updated as well.

What am I doing wrong(I believe this is going to be one of those coding bloopers I will fondly remember...one day)?

My Code: This is the object the values are assigned to:

UOPSim: Sim = {
    simId: null,
    simType: '',
    imageUrl: '',
    simCustomName: '',
    simDescription_Line1: '',
    simDescription_Line2: '',
    simDescription_Line3: '',
    simDescription_Line4: '',
    peakGigLimit: null,
    peakAmount: null,
    monthlyGigLimit: null,
    monthlyAmount: null,
};

This is my method:

onAddSimToCart(sim) {
    if (sim.simType === 'UOP') {
      this.UOPSim.simId = this.simsInCart.length + 1;
      this.UOPSim.simType = sim.simType;
      this.UOPSim.simCustomName = sim.simCustomName;
      this.UOPSim.peakGigLimit = sim.peakGigLimit;
      this.UOPSim.peakAmount = sim.peakAmount;
      this.UOPSim.monthlyGigLimit = sim.monthlyGigLimit;
      this.UOPSim.monthlyAmount = sim.monthlyAmount;
      this.simsInCart.push(this.UOPSim);
    } else {
        // do stuff
    }
}

Thank you in advance!

Andrew Allen
  • 6,512
  • 5
  • 30
  • 73
onmyway
  • 1,435
  • 3
  • 29
  • 53
  • 1
    you are using one variable that you are pushing in an array, the same object over and over. – AT82 Sep 13 '19 at 11:24
  • 1
    `this.simsInCart` is just an array containing multiple references to the same object, `this.UOPSim`. – jonrsharpe Sep 13 '19 at 11:25

2 Answers2

1

In case someone happens upon this question, this is how I resolved my issue:

As per @mbojko answer that was posted, I was simply referencing the same Object (newb move!).

I solved this by simply doping the following:

If you want shallow copy, use Object.assign({}, a)

For "deep" copy, use JSON.parse(JSON.stringify(a))

*Thanks to @Tareq for his answer to the post here: How do I correctly clone a JavaScript object?

So in my case I changed this.simsInCart.push(this.UOPSim); to:

const newSim = JSON.parse(JSON.stringify(this.UOPSim));
this.simsInCart.push(newSim);
onmyway
  • 1,435
  • 3
  • 29
  • 53
-1

Angular and TypeScript have nothing to do with that. It's simple JavaScript:

      this.simsInCart.push(this.UOPSim);

If the components keep one UOPSim, then you don't have n objects in your array, you have n references to the same object.

You can clone it one way or another:

      this.simsInCart.push({ ...this.UOPSim });
mbojko
  • 13,503
  • 1
  • 16
  • 26