Adjusting the information of a fresh element within an array will subsequently impact all other elements within

I have a problem with my Angular application where I need to add new elements to an array. The array is shown on the GUI after clicking a button.

Here is how my current array looks:

[ {name: 'user1', percentage: '1'} ]

But after clicking the button, I want the array to look like this:

[ 
   {name: 'user1', percentage: '1'}, 
   {name: 'user1', percentage: '0'} 
]

The issue I'm facing is that adding another element changes every percentage to 0 like so:

[ 
   {name: 'user1', percentage: '0'},
   {name: 'user1', percentage: '0'} 
]

This is the code for my array and the function to add a new element:

accData:any = [];

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

    console.log(this.accData)
  }

Answer №1

JavaScript uses reference semantics.

The items within your array act as pointers to objects stored on a heap memory. It is important to create a new object and place it into the array instead of duplicating an existing pointer.

One elegant method to duplicate an existing object while allowing for property modifications is through Object spread syntax.

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

It should be noted that Object spread syntax performs a shallow copy, which suffices for simple objects. However, if you have nested properties, a deep copy may be necessary.

Answer №2

please review the following code snippet:

const accountInfo = [ {username: 'user1', balance: '100'} ];
accountInfo.push({username: accountInfo[0].username, balance: (parseInt(accountInfo[0].balance) - 10).toString()});

console.log(accountInfo);

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

Is the latest Swiper JS version compatible with outdated web browsers?

Seeking information on browser compatibility. I am interested in upgrading to the latest version 8.4.5 of Swiper JS for my project, currently using version 4.1.6. Upon examining their shared Github repository file .browserslistrc, I noticed changes that ta ...

When accessing a REST API in an Angular 16 project, errors may occur. However, if the API is directly called via POSTMAN or a browser, the expected data will be displayed

angular project using service for data retrieval fetchData() { this.regionService.getAllRegion().subscribe(data => { this.regionValue = data; })} Fetching Data from the API Endpoint getAllRegion(): Observable<RegionI> { const regionUrl ...

ERROR: Unhandled promise rejection: Route cannot be found. URL Segment: 'details'

My current setup involves a router configuration in my Angular application. Below is the code snippet showcasing my router settings: import { Route, RouterModule } from '@angular/router'; import { ProjectDetailsComponent } from '../componen ...

Error message "Property shorthand expected in object literal" occurs when assigning a value to a variable as an object

Here is an example of an object that I have: { element: 'tool-app', file: '/tool-app.js', icon: 'csr-icon', name: 'Planning view', id: 'planning-view' } To simplify thi ...

The MaterialModule export could not be located

After installing the Angular Material Library, I encountered a Module not found error. Can anyone provide a solution for this issue? Thank you. material-module.ts import { NgModule } from '@angular/core'; import { A11yModule } from '@angula ...

Executing TypeORM commands yields no output

It's been a while since I last tested my Nest project with TypeORM, and now when I try to run any TypeORM command, nothing happens. I attempted to run TypeORM using these two commands: ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js ...

What is the best way to divide a single file Angular module into separate client-side, server-side, and shared files?

When working on an Angular 4 project scaffolded by dotnet-cli, the module artefact is split into three files: one for shared components, one for server-related components, and one for client-specific components. These files are named as follows: <module ...

Angular 14: A collection and schematic must be provided for execution to proceed with the process

I've recently started learning angular. After installing the latest version, I created an app called "test" using the command ng new test. Next, I opened the app in Visual Studio Code and tried to create a new component by entering the command: ng g ...

The evaluation of the Angular getter takes place prior to the constructor being executed

constructor( private readonly authService: SocialAuthService, private readonly authS: AuthService, private readonly loginS: LoginService, private readonly router: Router, private readonly formBuilder: FormBuilder, ) { alert(' ...

Dramatist - shutting down an angular pop-up dialog

I am currently utilizing the Playwright tool to carry out testing on an angular application. One particular scenario involves a modal that is displayed by default when a page is loaded. Despite my best efforts, I have been unable to successfully close this ...

Tips for securing an Angular+Express application from theft while running offline

<pDuring the previous year, I created a basic application using Angular, Express, and SQLite for a local Warehouse (Logistics Hub). This app was used to monitor daily truck arrivals and departures, including details such as weight and ori ...

The Date Filter is causing a glitch in formatting the date value

I have a variable called dateSubmitted with the value of "dateSubmitted": "07-09-20:11:03:30" Currently, I am utilizing Angular Version 7 Within my HTML code, I am using the date filter to format the date like so: <td> {{element.dateSubmi ...

Navigating SSL certificate prompts in Protractor

Our programs utilize SSL certificates and we are unable to bypass Chrome's prompt for selecting a certificate. We would be satisfied with simply choosing the one certificate needed. Attempts have been made using this code: capabilities: { browser ...

What is the best way to set up TSLint to apply specific rules with one line and different rules with another line

There is a unique method in which I can specify the code to format, such as forcing the else statement to be on the same line as the ending brace of an if statement. "one-line": [ true, "check-open-brace", "check-catch", "check-else", "check-fin ...

Using AMCharts with Angular but encountering an issue where there is no data present in the array within the AM

Utilizing a chart from AMCharts within an Angular component has raised some challenges. Although a data array is successfully passed into the component template, it appears empty when accessed inside the AMCharts code. This puzzling issue occurs in the p ...

Encountering difficulties while utilizing Ramda in typescript with compose

When attempting to utilize Ramda with TypeScript, I encountered a type problem, particularly when using compose. Here are the required dependencies: "devDependencies": { "@types/ramda": "^0.25.21", "typescript": "^2.8.1", }, "dependencies": { "ramda ...

Exploring Cypress Component Testing within a NextJS project

Could someone assist me with understanding how to utilize the cypress plugin for nextJS in order to execute Cypress Components Test package.json "devDependencies": { "@cypress/react": "^5.3.4", "@cypress/webp ...

Enable child classes to overwrite using either a function attribute or a method

class Foo { foo: () => void } class Bar extends Foo { foo() {} } Is there a way in which TypeScript can be configured to allow the scenario described above? Playground The 'Foo' class defines a property 'foo' as an instance ...

"Firebase function fails to return Typescript class variable, resulting in 'undefined'

Being someone with a background in python/golang, I am now delving into ionic2. There seems to be an issue that I can't quite figure out due to my current level of knowledge in this stack. Perhaps I just need a way to reference the outer scope of this ...

Error encountered when attempting to upload a file using Angular and Firebase: "[object Object]"

UPDATE : After some investigation, I finally discovered the solution which required specifying the file name in the reference : this.fireStorage.storage.ref(file.name).put(file); I have been attempting to upload a file to FireStorage, but I am encounteri ...