Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

typescript when i change data of new element in array it changes every element

I’m working with angular and i want to add new elements in an array i display on gui after i click a button. My array looks like this
[ {name: 'user1', percentage: '1'} ] and after i click the button i want the array to be
[ {name: 'user1', percentage: '1'},{name: 'user1', percentage: '0'} ]
My problem is adding the other element change every percentage to 0 like this
[ {name: 'user1', percentage: '0'},{name: 'user1', percentage: '0'} ]

My array is defined like this
accData:any = [];
and my add new element function is this

new(){
    
    this.accData.push(this.accData[this.accData.length - 1]);
    this.accData[this.accData.length - 1].percentage = '0';

    console.log(this.accData)
  }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

JS has reference semantics.

The elements in your array are references to objects located on a heap.
You need to create a new object and add it to the array, not copy an existing reference.

Object spread syntax is an elegant way to copy existing object, and allows to change some props.

const accData = [ {name: 'user1', percentage: '1'} ];
const newElem = {...accData[accData.length - 1], percentage: '0'};
accData.push(newElem); // newElem can be inlined for brevity

Note that Object spread syntax makes a shallow copy – this is enough for your objects, but you may need a deep copy if you have nested properties.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading