how can i delete something from a object in localstorge in javascripts?

i was working on a online shop . now everything is good but i want to do something to delete a product from my cart .here is its code can you help me?

function displaycart() {
        let cartitems = localStorage.getItem("productsincart");
        cartitems = JSON.parse(cartitems);
        let productcontainer = document.querySelector(".products-container");
        let cartcost = localStorage.getItem("totalcost");
        if (cartitems && productcontainer ) {
            Object.values(cartitems).map(item => {
                productcontainer.innerHTML += '<tr><td><button class="bd">close</buttton></td><td>'+ item.nam + '</td><td>' + item.price * item.incart + '</td><td>' + item.incart + '<td>افزودن</td></tr>'
            });

            let productmab = document.querySelector(".mabb");
            productmab.innerHTML += cartcost;
            
        }
    }

    let bv = document.querySelector(".bv");
    let bd = document.querySelectorAll(".bd")
    let cc = localStorage.getItem("productsincart")
    let cartiteme = JSON.parse(localStorage.getItem("productsincart"))
    bv.addEventListener("click" , () => {
        localStorage.clear()
        window.alert("refresh the page")
    })
    displaycart()

and here is the localstorge …

how can i delete one of them in productsincart ?

Answer

One way is to give them ids. You could use npm i --save uuid to get random ids.

Your local storage should look like this:

[{"id": "342324", "product": "item"}, /* then repeated for every item */]

Then you remove the entry by creating a new array that doesn’t contain the object with the specified id, then you replace the previous local storage array with the new one. You can filter like this:

const newLocalStorage = JSON.parse(localStorage.getItem("productsincart").filter((product) => product.id !== id);.

Then set local storage to newLocalStorage.