Using localStorage
, I have stored multiple objects in an array. Is there a way to remove just one object from this array?
If I use
localstorage.removeItem(keysofthelocalstorage)
, I can delete the entire array, but I specifically want to remove only certain items.
For instance, if the key for my entry in local storage is basketContent
and the value looks like [{object1},{object2},{object3}]
, how can I delete {object1}
? Do I need to assign a different key to reference this object in the array?
I'm able to access the object I wish to delete with a "delete" button click event, but actually removing it has been troublesome. I've attempted using slice
without satisfactory results. Here's the relevant portion of my code:
let basketContent = JSON.parse(localStorage.getItem("basketContent")); // Parses JSON data
// console.log(basketContent);
if (basketContent !== null) {
for (let i = 0; i < basketContent.length; i++) {
const tabsLine = document.createElement("tr");
const deleteButton = document.createElement("button");
deleteButton.setAttribute("class", "btn btn-danger mt-1") ;
deleteButton.innerHTML = "delete";
const tbody = document.getElementById("bodytabs");
tbody.appendChild(tabsLine);
tabsLine.appendChild(deleteButton);
console.log(basketContent);
/////////////////////// on click ///////////////////////
deleteButton.addEventListener("click", function() {
console.log(baksketContent); // Displays the array of objects
console.log(basketContent[i]); // Displays the specific object
});
}
} else {
console.log("empty busket");
}