SeventhWarhawk
SeventhWarhawk

Reputation: 1323

How to remove a specific object within an array of objects in local storage? (Angular 10+)

I have an array of objects (each object being an individual users' details), stored in my local storage and thereafter displayed in a user table. I want to remove a specific object within this array of objects in local storage when the delete button for that objects record (as seen on the table) is clicked. So what i believe should happen; when the delete button for a specific object record is clicked on the table, the objects position in the array should be sent to a delete function which will then use the removeItem method from local storage to delete the object at that position within the array of objects.

The local storage looks as follows:

enter image description here

The delete button (found on every object record on the table)

<button mat-menu-item (click)="deleteUser()">Delete User</button>

The delete function:

ngOnInit(): void {
    this.user = JSON.parse(localStorage.getItem('Users') || '{}');
    this.userDataSource = new MatTableDataSource(this.user);
    this.deleteUser()
  }

  deleteUser() {
    localStorage.removeItem('Users')
  }

I simply have no idea how i would just delete "2: Object" for example, without clearing the entire local storage (which is what the above deleteUser function does).

Upvotes: 1

Views: 1160

Answers (1)

Vishesh Gautam
Vishesh Gautam

Reputation: 186

A simple approach.

yourData = JSON.parse(localStorage.getItem("Users"))

yourNewData = []

for(i=0; i<yourData.length; i++) 
{ 
    if(yourData[i].yourKey !== "UserIDYouWantToDelete")
        {
            yourNewData.push(yourData[i]);
        }
}
localStorage.setItem("Users", JSON.stringyfy(yourNewData))

However, this can be inefficient if you're dealing with large amount of data, you may want to look at Splice Method here.

Upvotes: 1

Related Questions