you may use callback function return key > 0
Aug 30, 2018
5
Level 1
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?
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
Please or to participate in this conversation.