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