How to Edit / Delete data from HTML Table and LocalStorage stored as an array of objects? [closed]

I’m making a modal popup based registration form where, when I insert any user, their data must be displayed in a HTML Table and at the same time the data must be stored in a local storage as an array of objects. In the table, with the user data, every row of data must have two action buttons which are EDIT and DELETE.

When I click on delete the selected row’s data must be deleted from both the table and the local storage. Also the table must show id as a length of array of objects. So that when I delete 2nd row, only 2nd row shall get deleted, not the other ones and when I try to insert new row of data, the table or array must continue from where it stopped last. Like if I have 6 arrays of objects, if I delete 2nd row, then if I insert new user, it must store in a 7th row.

Same goes for Edit button, that when I select 2nd row, the modal form must popup with 2nd row’s values in it. And when I change it, the selected row in the table and the array of local storage must be updated. Only the selected row shall get selected and updated.

I tried to do the same but my edit and delete won’t go well, please help me with it.

  • I’m new to stack overflow, can anybody tell me how can I insert my code in the question?

    – 

  • Please read this question along with all the answers to gain a better understanding about How to Ask questions on StackOverflow.

    – 

  • Also, please read How to Create a Minimal, Reproduceable Example

    – 

  • To insert the code in your question, Edit your question, and add your Minimal, Reproduceable Example as text within your question.

    – 

Based on the scenarios, below are the cases observed –

  1. Assuming you have a method that populates the data to the table and also saves the data to the local storage.
  2. Write a delete method, passing the index for the selected row to be deleted, find the index in the array and delete it using splice or filter, save the updated array to the local storage and call back the method that populates/updates the table data. (The populate method that uses the updated array as input.
  3. Same goes for edit operation, pass the index, update the array, save to local storage, call the populate method for table.

Below is the delete example based on the shared scenario, providing the exact code may help to provide further details.

function deleteUser(id) {
const usersData = getDataFromLocalStorage();
const indexToDelete = usersData.findIndex(user => user.id === id);
if (indexToDelete !== -1) {
usersData.splice(indexToDelete, 1);
localStorage.setItem('userData', JSON.stringify(usersData));
populateTableData();
}
 }
function getDataFromLocalStorage()
{
const data = localStorage.getItem('userData');
return JSON.parse(data) || [];
 }





 

Leave a Comment