How do I remove a specific object from my localStorage array in Angular?

Currently, I am storing and retrieving form values from localStorage. When displaying the data, I want to be able to remove a specific object that is clicked on. The issue is that my current code removes all the data instead of just the selected object. Below is an example of the policy value:

"beneficiaryInfo":[
      {
         "name":"test",
         "surname":"test2",
         "personalNumber":"02027041738",
         "phone":"5685522555"
      },
      {
         "name":"test3",
         "surname":"test5",
         "personalNumber":"02027041738",
         "phone":"5685522555"
      }
   ]

.html

<div *ngFor="let u of user.beneficiaryInfo">
            <span>
              {{u.name}} {{u.surname}}
            </span>
    <div class="del" (click)="del()">
    </div>
  </div>

.ts

get user(): any {
    return JSON.parse(localStorage.getItem('policy'));
}

del() {
    updateLocalStorage('policy', removeValueFromObject<Policy>(getFromLocalStorage<Policy>('policy'), 'beneficiaryInfo'));
}

helpers.ts

export const updateLocalStorage = (storageKey: string, object: object) =>
    localStorage.setItem(storageKey, JSON.stringify(object));

export function getFromLocalStorage<T>(storageKey: string): T {
    return JSON.parse(localStorage.getItem(storageKey));
}
export function removeValueFromObject<T>(object: T, key: string): T {
    delete object[key];
    return object;
}

Answer №1

The `beneficiaryInfo` array is completely removed by the `del` function. To remove a specific object from the array, you must specify the index or id.

In your template, declare the index and pass it as an argument to your delete method in order to remove the object at that index from the list.

    <div *ngFor="let u of user.beneficiaryInfo; index as i">
        <span> {{ u.name }} {{ u.surname }} </span>
        <div class="del" (click)="del(i)"></div>
    </div>

In the controller, the delete method can be implemented as follows:

    del(index: number) {
        const data = JSON.parse(localStorage.getItem('policy') as string);

        const newData = {
            ...data,
            beneficiaryInfo: data.beneficiaryInfo.filter((_: any, i: number) => i !== index)
        };

        localStorage.setItem('policy', JSON.stringify(newData));
    }

UPDATE

To remove the `beneficiaryInfo` property if the list is empty, a check needs to be performed and the property should be removed using destructuring:

    del(index: number) {
        const data = JSON.parse(localStorage.getItem('policy') as string);

        const beneficiaryInfo = data.beneficiaryInfo.filter((_: any, i: number) => i !== index);

        let newData: MyDataType;

        if (beneficiaryInfo.length > 0) {
            newData = { ...data, beneficiaryInfo };
        } else {
            const { beneficiaryInfo, ...partialData } = data;
            newData = partialData;
        }

        localStorage.setItem('policy', JSON.stringify(newData));
    }

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

How can I emphasize the React Material UI TextField "Cell" within a React Material UI Table?

Currently, I am working on a project using React Material UI along with TypeScript. In one part of the application, there is a Material UI Table that includes a column of Material TextFields in each row. The goal is to highlight the entire table cell when ...

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

Using Angular to parse intricate JSON data

Need help parsing an http request in the following format: [ { "id": 1, "date": "2022-01-13T00:00:00.000+00:00", "time": "2022-01-13T21:21:21.000+00:00", "office&quo ...

The name 'BrowseAnimationModule' cannot be located

Can someone help me figure out how to install or fix this import issue I'm having with the 'animations' directory in @angular/platform-browser/animations not importing properly? import {CommonModule} from '@angular/common'; import ...

Creating a stream of observables in RxJs and subscribing to only the latest one after a delay: A comprehensive guide

I am trying to create a stream of Observables with delay and only subscribe to the last one after a specified time. I have three HostListeners in which I want to use to achieve this. I would like to avoid using Observable form event and instead rely on H ...

Inheritance of Generic Types in TypeScript

Could someone assist me in understanding what is incorrect with the code snippet provided here? I am still learning Typescript. interface ICalcValue { readonly IsNumber: boolean; readonly IsString: boolean; } interface ICalcValue<T> ex ...

The compatibility between `webpack-streams` and `@types/webpack`

I encountered an issue with my gulpfile while building it with TypeScript. Everything was working fine until I included @types/webpack-stream. Suddenly, I started getting a series of errors that looked quite ugly: node_modules/@types/webpack-stream/index.d ...

Evaluating h1 content in HTML using Angular Protactor testing

I am completely new to end-to-end testing. I have a login page in my application that should be displayed to users when they log out. However, I am facing an issue with retrieving the text from a specific div element containing an h1 tag, leading to unexpe ...

There is no way for me to view my loader more than once

I am currently utilizing @ng-bootstrap/ng-bootstrap for pagination and ngx-loading to handle loader display. Both of these components are performing well in my application. Here is the code snippet for pagination: {{ loading }} <ngb-pagination [colle ...

When I refresh the page in Angular2, the router parameters do not get loaded again

When loading my application on routers without parameters, everything is normal. However, when trying to use a router with params, the application fails to load. For example: localhost:3000/usersid/:id The code for the router is as follows: const appRou ...

Employing distinct techniques for a union-typed variable in TypeScript

I'm currently in the process of converting a JavaScript library to TypeScript. One issue I've encountered is with a variable that can be either a boolean or an array. This variable cannot be separated into two different variables because it&apos ...

Learn the proper way to specify the return type of a function as a class, rather than an instance, in Typescript

Is there a way to declare that a function returns a generic class definition? I have tried the following for non-generic classes, but it does not work for generic ones: export function composeAll(composeFunction: Function, depsFunction: Function): (compon ...

Switch up a button counter

Is there a way to make the like count increment and decrement with the same button click? Currently, the code I have only increments the like count. How can I modify it to also allow for decrements after increments? <button (click)="toggleLike()"> ...

When incorporating leaflet-routing-machine with Angular 7, Nominatim seems to be inaccessible

Greetings! As a first-time user of the Leafletjs library with Angular 7 (TypeScript), I encountered an error while using Leaflet routing machine. Here is the code snippet that caused the issue. Any ideas on how to resolve this problem? component.ts : L. ...

What is the process for assigning a predefined type that has already been declared in the @types/node package?

Is there a way to replace the any type with NetworkInterfaceInfo[] type in this code snippet? Unfortunately, I am unable to import @types/node because of an issue mentioned here: How to fix "@types/node/index.d.ts is not a module"? Here is the o ...

Tips for managing the output of an asynchronous function in TypeScript

The casesService function deals with handling an HTTP request and response to return a single object. However, due to its asynchronous nature, it currently returns an empty object (this.caseBook). My goal is for it to only return the object once it has b ...

Tips for generating a fixed-length array from multiple arrays with different lengths, focusing on selecting items from each array according to their significance

In order to create a quiz, I am looking to extract 'questions' from various 'topic' arrays. These topics are selected based on the user's preference and are used to populate a question bank for a 20-question quiz. The topics rated ...

History will still store CanActive URL even if it returns false

Why does CanActive add the skipped path to history? I'm using the following guard: canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean { if (this.router.url === '/') { thi ...

Converting Scss to css during the compilation process in Angular

Seeking assistance with .css and .scss file conversion. I am in need of help with generating or updating a .css file from an existing .scss file during compilation. To explain further: when writing code, everything is going smoothly until I decide to save ...

Anticipating the resolution of promises and observables in Angular 2

Within my accountService module, there is a dialog prompt that requests the user's username and password, returning a promise. If the user clicks on close instead of dismissing the dialog box and the validators require the input data before allowing t ...