1

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

2
  • You could create a new JSON object by filtering out the ones you don't want, then re-save the new object stringified. Commented Apr 27, 2021 at 20:59
  • in delete function get local storage, filter it and set it again deleteUser() { var local = localStorage.getItem('Users'); if (local) { var users = JSON.parse(local); //you need to filter your local storage and save it again, choose whatever your filter is below is just sample var localStorage = users.filer(i => i.id !== this.user.id); localStorage.setItem("localStorage", JSON.stringify(localStorage)); } } Commented Apr 27, 2021 at 20:59

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.