How to address duplicate array objects when using splice in Angular 4

For the purpose of this question, I have simplified some code.

    this.getDataRuleList.splice(this.count, 1, dataRuleData);
    console.log(this.getDataRuleList);
    this.count += 1;

The getDataRuleList function is responsible for returning an array of objects from a service. It is seamlessly bound to a PrimeNg TurboTable.

    // get method to retrieve service collection
    get getDataRuleList(): IDataRule[] {
      return this._dataRuleListService.dataRuleList;
    }

Whenever I attempt to edit a row and update an object within my bound array (getDataRuleList) by replacing it entirely with a new object, all elements in the array end up being identical to the newly inserted value. Despite providing different values each time (dataRuleData), the issue persists. I suspect that it has something to do with references, but how can I prevent this from occurring?

View image showcasing the problem

Answer №1

One way to create a replica of an object is to clone it

const copiedData = Object.assign({},originalData);
this.getOriginalDataList.splice(this.amount, 1,copiedData);

If you require a deep copy, you can refer to this sample

const deepCopiedData = JSON.parse(JSON.stringify(objectToClone));

Answer №2

Utilize the es6 splice operator to create a clone.

illustration

const clonedData = {...dataRuleData};

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

Creating a ref with Typescript and styled-components: A comprehensive guide

Trying to include a ref into a React component looks like this: const Dashboard: React.FC = () => { const [headerHeight, setHeaderHeight] = useState(0); const headerRef = React.createRef<HTMLInputElement>(); useEffect(() => { // @ts ...

TypeScript introduces a flexible generic type, Optional<T, Props>, allowing customized props for a specific

In my attempt to develop a type called Optional<T, TProps>, where T represents the initial type and TProps is a union type of properties that need to be optional. As an illustration: type A = Optional<{a: string, b: string}, 'a'&g ...

Unable to assign a value to the HTMLInputElement's property: The input field can only be set to a filename or an empty string programmatically

When attempting to upload an image, I encountered the error message listed in the question title: This is my template <input type="file" formControlName="avatar" accept=".jpg, .jpeg .svg" #fileInput (change)="uploa ...

Guide on how to connect several Subjects within an object literal to their corresponding Observables in another object literal

I am currently developing a class using Angular and I need to share multiple states associated with that class. To accomplish this, I have created several instances of BehaviorSubject private subjects = { a : new BehaviorSubject<A>(this.a), b ...

Preserve the checkbox state upon refreshing the page

I am facing an issue with keeping the checkbox state saved after a page reload. Currently, I have stored my unchecked checkboxes in localStorage, but I am unsure about what steps to take next. In simple terms, I want the checkbox to remain unchecked when I ...

Ensuring Generics are Required in your Code

Can Generics be marked as mandatory in typescript? function validateGenerics<Result, Variables>({ foo, bar }: { foo: Result bar: Variables }) { console.log(foo, bar) } // Attempting to call the function without passing Gener ...

The value returned by Cypress.env() is always null

Within my cypress.config.ts file, the configuration looks like this: import { defineConfig } from "cypress"; export default defineConfig({ pageLoadTimeout: 360000, defaultCommandTimeout: 60000, env: { EMAIL: "<a href="/cdn-cgi/ ...

The bar chart functions perfectly on localhost but encounters issues after being hosted on Gitpage

Localhost Gitpage The bar chart was displaying correctly on localhost, but once it was hosted on Gitpage, it began to show issues. Any suggestions on how to resolve this? Repository Link: https://github.com/mzs21/bar-chart Live Preview: ...

Unable to display nested objects retrieved from a JSON API in Angular

How can I retrieve images from an API and properly access the specific object within the object? Any tips would be greatly appreciated! API Endpoint: This is how my interface is structured: export interface MovieModel { id: number; name: string; ...

Utilizing *ngFor to display elements with odd indices

Within my Angular application, I have successfully used a loop to populate the 4 employeeList components. Here is the code snippet: <div *ngFor="let record of records"> <p-panel> <div comp-employeeList [listFilter]="record.Filte ...

How do I set class properties in TypeScript using an array of values for initialization?

My constructor has the following structure: constructor(values: Object = {}) { //Constructor initialization Object.assign(this, values); } However, it currently requires named initialization like this : new Inventory({ Name: "Test", ...

Is there a way for me to add a clickable link within a tooltip?

In my title, I want to insert a clickable link like 'Link' or 'a'. The title is ready for any string you input. <MaterialSwitch title={CLICKABLE STRING HERE} /> ...

Remove an item from the DOM instantly with React

Having trouble synchronously removing a child from the container? Here is a simplified code snippet demonstrating the current solution using the useState hook. type ChildProps = { index: number; id: string; remove: (index: number) => void; }; fun ...

Issue with Angular 5 Application - "Implementations cannot be declared in ambient contexts"

Recently in my Angular 5 project, I started encountering an issue with the observable object. Everything was working smoothly until about a week ago when I began receiving this error message: ERROR in node_modules/rxjs/Observable.d.ts(20,31): error TS1183 ...

Arranging Objects in Angular 2 using Pipes

While I've come across similar questions, none of the solutions provided have worked for me so far. Therefore, please refrain from marking this as a duplicate unless you can point me to an answer that actually resolves my issue. Currently, I am worki ...

Check if a value is present in the array with *ngIf

I'm curious about how to use the ngIf directive in a specific scenario. In my Angular application, I have dynamically generated angular material toggles, each with a unique id. I'm familiar with using ngIf to conditionally display elements on the ...

What are the benefits of initializing my Angular2 reactive form in the constructor instead of ngOnInit?

According to several responses, it is recommended to initiate the initial functions of an Angular2 application within the ngOnInit() method, reserving the constructor specifically for dependency injection tasks. However, the Reactive Forms tutorial I am c ...

Creating consistency in tab spacing within a text area

At the moment, I am utilizing an HTML textarea attribute to collect input from users and then displaying that text back to them formatted. However, there seems to be an issue with how it handles tabs. For instance, when attempting to input the following: ...

The Vuex MutationAction decorator cannot be assigned to a TypedPropertyDescriptor

I am a beginner in Typescript and apologize in advance if this is a rookie mistake. I am struggling to resolve this TS error: @Module({ namespaced: true, name: "Admin" }) class Admin extends VuexModule { public adminUserList: UserList = []; ...

Retrieve the mfData value from the TypeScript file in order to perform operations on it within the Angular 2 framework

I have a snippet of code that iterates through data from stacklist_table, which is a JSON array, and displays it in a table format. The stacklist_table contains a full list of objects, but I only need a subset of these objects so I have applied some filter ...