I am attempting to remove an element from an array stored in local storage. I am using vanilla JavaScript within a Vue.js 3 component. Here is my array
:
["96", "281", "287", "415", "650", "661", "378", "295"]
When I click on my trash icon:
https://i.stack.imgur.com/s0nsh.png
I have a function to delete the selected row:
const removeItem = (event) => {
let itemId = event.target.parentElement.parentElement.children[0].id;
console.log(itemId)
// Saving IDs in LocalStorage to send to controller in next steps.
// First, delete all content from LocalStorage.
const existingEntries = JSON.parse(localStorage.getItem("items_ids"));
existingEntries.splice(itemId, 1);
localStorage.setItem("items_ids", JSON.stringify(existingEntries))
addItemCart.value = addItemCart.value.filter(item => item.id != itemId);
}
I need to update my array
in localStorage
. With this code, it does not delete the index and does not update my data.
Thank you for reading and apologies for my poor English.
Update:
With the accepted response, I was able to modify my code so that it runs smoothly and looks much cleaner:
const removeItem = (event) => {
let itemId = event.target.parentElement.parentElement.children[0].id;
// Saving IDs in LocalStorage to send to controller in next steps.
// First, delete all content from LocalStorage.
addItemCart.value = addItemCart.value.filter((item) => item.id !== itemId);
let newArrayIds = []
addItemCart.value.forEach(element => {
newArrayIds.push(element.id)
});
localStorage.setItem("items_ids", JSON.stringify(newArrayIds));
}
With this code, my table and localStorage are updated correctly.