Changing one object property in an array changes all object properties

I have an Addon-model that has two properties - name:string and selected:bool. I store those in an array called addons. I have this as a property for another object (CartItem). When I change the selected property one of the addons, it is changed in all of the addons in that array. I want every array of addons in each CartItem to have its unique combination of Addons.

I’ve been pulling all-nighters over this issue and it’s driving me crazy! I think that I’m missing some details here…

I don’t expect anybody would be able to help without seeing code.

I’m so sorry for that! Here are some screenshots.

Here is the code for the .ts file:

And here is the code for the .html

@aladinsane You can pass the click call to your .ts file and inside it, before and after changing the selected value, print the addons array to see what is changed in fact, and how many times it is called. If I understood correctly what is happening, it should’t happen with the code you posted. So try to log the values with something like:

onToggleSelected(addon: Addon) {
	addon.selected = !addon.selected;

And in your html file:


I’ve used JSON.stringfy() to know the state before changing (logging the object direcly display the current values).

Such behaviour that you exposed seems like the addons objects are the same instance (do you create a new object for each addon or reuse the same object?), or that the click event was called for the other addons too (strangely tough). So, in your case, I think the best approach is try to find the cause in some way like the one I mentioned.


Hi @lucasbasquerotto,

Thank you for your reply, I’m currently debugging to see if the problem persists. I have a follow-up question on JSON.stringify.

If I JSON.stringify and object and then JSON.parse it on the other page, are the references broken (i.e. does it count a new object?) or does it return to having the same references as before?


@aladinsane The references will be different because JSON.stringify just transform the object to a string, expanding the references until the primitive values (be aware that circular references cause errors). JSON.parse will create a band-new object with new objects inside it with the same primitive values.

How will the application know which objects to reuse? The string could be retrieved from a text file or an external server, for instance.

But I don’t see the necessity of calling JSON.stringify and JSON.parse at all if you use the Ionic2 navigation methods push and setRoot, because you can pass the object itself. Ionic2 (and Angular2 basically) is a SPA (Single Page Application), so when you go to a new page, the web page itself is not changed, just what the user see (and some navigation stuff behind the scenes), so you can just pass the object to the other page as a param.