Strategies for handling a collection of objects with immutability

Using TypeScript, I am trying to manage a list of objects without relying on ngrx and with immutability. As an example, this is how I'm approaching it:

    let items = <any>[];
    let item1 = { n: 'toto' };
    // ADD item1
    items = [...items, item1];
    // Find item
    const item1Find = items.filter((v) => v.n == 'toto')[0];
    // Update item
    item1Find.n = 'titi';
    // Update item with immutability
    items = [...items, item1Find];
    //
    console.log('items', JSON.stringify(items));   // [{"n":"titi"},{"n":"titi"}]

However, the issue I'm facing is that I end up with duplicates of the modified object! Can anyone offer some assistance in understanding why this is happening?

Answer №1

When you work with objects and arrays in JavaScript, it's important to remember that they are passed by reference. This means that when you make changes to them, you are actually modifying the original item they point to. It's like having an arrow pointing towards the object - changing the arrow doesn't change the object itself.

In the example given, item1Find is a reference to the object item1.

const item1Find = items.filter((v) => v.n == 'toto')[0];

So, any modifications made to item1Find will also affect the underlying object it references, which in this case is item1. Creating an array with both item1 and item1Find simply results in duplicates of the same object.

This behavior is a common pitfall in JavaScript programming and it's important to clone objects if you want to modify them independently. Unless you specifically intend to leverage this reference behavior, it's usually best to create copies of objects before making changes. You can find efficient ways to deep clone objects in JavaScript for your specific use case in this post.

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

Tips for determining the defaultValue type in React.context usage

'use client'; import { useState, createContext, useMemo } from 'react'; type MessageStatus = 'default' | 'success' | 'error'; export type MessageProps = { type: MessageStatus; payload: string; }; ty ...

Steps to create a personalized loading screen using Angular

I am looking to enhance the loading screen for our angular 9 application. Currently, we are utilizing <div [ngClass]="isLoading ? 'loading' : ''> in each component along with the isloading: boolean variable. Whenever an API ...

Render JSON value as an input in an Angular component using @Input()

In my app.component.html file, I have included the following template: <test [someInput]="data"></test> The 'data' variable is a JSON object property structured like this: let data = {hello: "ciao"} Below is the code from my test. ...

Toggle the enableCheckboxSelector based on a specific condition

In my implementation of angular slickgrid, the enableCheckboxSelector is set to true by default in the grid options. However, I need to selectively hide checkboxes for all rows based on a dropdown value change. I tried the following code snippet: if(isRead ...

A step-by-step guide on generating a single chip using the same word in Angular

I'm trying to find a solution to ensure that only one chip is created from the same word inputted, instead of generating duplicates. Currently, users can input variations such as "apple," "APPLE," "apPPle," "aPpLe," and I want to automatically conver ...

Issue: Unable to resolve all parameters for LoginComponent while implementing Nebular OAuth2Description: An error has occurred when attempting to

I have been attempting to utilize nebular oauth in my login component, following the documentation closely. The only difference is that I am extending the nebular login component. However, when implementing this code, I encounter an error. export class Lo ...

Preventing duplicate namespace declarations in TypeScript

Let's say I have a variety of objects with the following data structure: { namespace: 'first'|'second'|'third' } Now, I need to include another object with the same data structure, but its namespace cannot be assigned ...

Can you define the classification of history in typescript?

Passing the routecomponentprops history to the helper function is now a go. This component is the core. const FinishEmailSignup: React.FunctionComponent<RouteComponentProps> = ({ history }) => { useEffect(( ) => { testEmailAuth(history) ...

Obtaining the host name in server-side rendering (

In the process of developing an app that consists of a client and an API hosted on different domains, the setup resembles the following: [Local] localhost:5000 (client) localhost:5001 (API) [Web] app.domain.com (client) api.domain.com (API) When mak ...

The undefined value of a Checkbox Change Event in Angular 8

I'm attempting to run a function when a checkbox is checked/unchecked, but I couldn't access the checkbox.checked property as it's showing as undefined. Here is the HTML: <input type="checkbox" (change)="eventCheck($event)" /> And h ...

Generating a random number to be input into the angular 2 form group index can be done by following these

One interesting feature of my form is the dynamic input field where users can easily add more fields by simply clicking on a button. These input fields are then linked to the template using ngFor, as shown below: *ngFor="let data of getTasks(myFormdata); ...

The Express server automatically shuts down following the completion of 5 GET requests

The functionality of this code is as expected, however, after the fifth GET request, it successfully executes the backend operation (storing data in the database) but does not log anything on the server and there are no frontend changes (ReactJS). const ex ...

Getting the value of a CSS Variable from Radix UI Colors with Javascript/Typescript: A step-by-step guide

Currently, I am attempting to dynamically retrieve the Radix Colors values in JavaScript. The reason for this requirement is that I generate these colors based on user input, resulting in values that are variable. As a result, I cannot hardcode the values. ...

Angular Service: Circular Dependency Problem Explained

Greetings, I am fairly new to the realm of Angular and have some background in AngualarJS (not very helpful here hahaha). Currently, I am referring to this resource to implement a Service/State for a specific Module. However, when attempting to use it wi ...

Encountering errors during 'npm i' - issues arising from unresolved dependency tree

Recently, I have been facing issues with running npm i as it keeps failing and showing an error. The project is using Angular 15 without any previous errors, so it's puzzling why there is suddenly a complaint about Angular 16. npm ERR! code ERESOLVE n ...

Update button Image upon click

Is there a way to swap the image on a button when it's clicked? I want my button to start with one icon, but then change to another icon once it has been clicked. How can I achieve this effect? Any suggestions on how to make this happen? Check out ...

Access to property 'foo' is restricted to an instance of the 'Foo' class and can only be accessed within instances of 'Foo'

In my Typescript code, I encountered an error with the line child._moveDeltaX(delta). The error message reads: ERROR: Property '_moveDeltaX' is protected and only accesible through an instance of class 'Container' INFO: (me ...

unable to retrieve / interpret data from herdsmen using fetch

When sending a request to a node server, the server responds with headers and a blank body. Despite being able to view the headers in the network activity panel within dev-tools, I faced difficulties reading them using the following code: let uploaded ...

Customize the element of the root node of a MUI component using the styled()

I am trying to implement the "component" prop with a MUI component (such as ListItem) using the styled() API. However, I am facing an issue where it says that "component" is not a valid prop. Can someone guide me on how to correctly achieve this? I have se ...

Tips for rendering nested objects and arrays within Angular 2

I am receiving JSON data from an API on the back-end and I want to display it using ngFor. However, when I tried to do so, I encountered an error message stating: "Cannot find a differ supporting object '[object Object]'" in the console. To addr ...