[英]Remove an item from an array inside a local storage object with javascript
I have the localStorage['cart']
and within it the array 'products'.我有localStorage['cart']
和数组 'products'。 The retrieve data from localStorage.getItem('cart')
looks like从localStorage.getItem('cart')
检索数据看起来像
{"products":
[
{
"id":"01",
"name":"Product Name 01",
"price":"Product Price 01",
"image":"Product Imagem 01"
},
{
"id":"02",
"name":"Product Name 02",
"price":"Product Price 02",
"image":"Product Imagem 02"
},
]}
I need, with an onclick=
event, remove a specific item in products
array, by using the id
.我需要通过onclick=
事件,使用id
删除products
数组中的特定项目。
EDIT编辑
var json = JSON.parse(localStorage["cart"]);
for (i=0; i < x; i++){
if (json.products.[i].id == id){
json.splice(i,1);
}
}
x are the json.products lenght. x 是 json.products 长度。
How can I do that?我怎样才能做到这一点?
This is the basic idea.这是基本思想。 Showing you how to parse the object from localStorage and how to write it back.向您展示如何从 localStorage 解析对象以及如何将其写回。
(function() { //prime cache var obj = { "products": [{ "id": "01", "name": "Product Name 01", "price": "Product Price 01", "image": "Product Imagem 01" }, { "id": "02", "name": "Product Name 02", "price": "Product Price 02", "image": "Product Imagem 02" }] }; localStorage.setItem("cart", JSON.stringify(obj)); }()); function removeItem(id) { var index = -1; var obj = JSON.parse(localStorage.getItem("cart")) || {}; //fetch cart from storage var items = obj.products || []; //get the products for (var i = 0; i < items.length; i++) { //loop over the collection if (items[i].id === id) { //see if ids match items.splice(i, 1); //remove item from array break; //exit loop } } localStorage.setItem("cart", JSON.stringify(obj)); //set item back into storage } console.log(localStorage.cart); removeItem("01"); console.log(localStorage.cart);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.