Summer Sale! All accounts are 50% off this week.

shifoodew's avatar

How to remove an object inside an array in browser local storage

This is the data structure of my local storage. How can I remove an object in the browser's local storage?

[{product_id: "287", name: "With Picture Muay Thai",…},…]
0:{product_id: "287", name: "With Picture Muay Thai",…}
1:{product_id: "288", name: "Way Picture", image: "/uploads/3OwG59WcBatVDNoHmSye1535107019.jpg",…}
2:{product_id: "289", name: "Naa Nay Picture", image: "/uploads/YFsEICj21MITE314HxTF1535107090.jpg",…}
3:{product_id: "290", name: "Walaaaaaa", image: "assets/images/product-default.png", price: "200.00"}

Like if the button has the value from 0 to 3, represent the key of an array object.

if the button has a value of 0, it will remove

0:{product_id: "287", name: "With Picture Muay Thai",…}

and update the new value of the local storage.

how to achieve that result?

0 likes
5 replies
newbie360's avatar

you may use callback function return key > 0

rawilk's avatar
rawilk
Best Answer
Level 47

You could find the index of the object and then use splice to remove it.

// this assumes you know the product id you are removing
const removeProduct = productId => {
    // get products from local storage
    let products = ...

    const index = products.findIndex(product => product.product_id === productId);

    if (index > -1) {
        products.splice(index, 1);
    }

    // store modified array back to local storage.
};

2 likes
shifoodew's avatar

@wilk_randall sorry for the late response. What if I have a product with the same product id? like

0:{product_id: "287", name: "With Picture Muay Thai",…}
1:{product_id: "288", name: "Way Picture", image: 
"/uploads/3OwG59WcBatVDNoHmSye1535107019.jpg",…}
2:{product_id: "289", name: "Naa Nay Picture", image: "/uploads/YFsEICj21MITE314HxTF1535107090.jpg",…}
3:{product_id: "290", name: "Walaaaaaa", image: "assets/images/product-default.png", price: "200.00"}
4:{product_id: "287", name: "With Picture Muay Thai",…}

so both product with ID 287 will be removed?

jlrdw's avatar

Just me, I'd loop over the array and put into a table to make it easier to work with.

Or put in a collection, anything but that. JS array's can be more tricky than php array's to deal with.

Just my opinion.

Or just re write whole array with the new data is an option, perhaps.

rawilk's avatar

@shifoodew - I would say that you need some other kind of identifier that is unique then. Or if you already know the index you can just use it with splice without trying to find it. It's a little difficult to provide a clear answer without knowing how you're actually using the array.

2 likes

Please or to participate in this conversation.