我有一个购物篮,上面有一个数组,我存储在本地存储中。如何检查特定值并增加或减少值
这是我的代码
我想检查ProductID是否存在,然后从中添加或减去,然后更新本地存储
var Basket = {
ProductID: product,
Quantity: quantity
};
//STEP 2 - create an array
//
var BasketContents = [];
if (localStorage.getItem('BasketContents') != null) {
BasketContents.push(JSON.parse(localStorage.getItem('BasketContents')));
}
//STEP 3 - create array of objects
BasketContents.push(Basket);
localStorage.setItem('BasketContents', JSON.stringify(BasketContents));
答案 0 :(得分:1)
您可以通过以下方法解决此问题:保存一个对象(称为对象ALL)的对象,将productId作为该对象(对象ALL)或每个对象数组(每个篮子)中每个对象的键。第二个(对象数组)感觉更直观,所以我会解释一下。
const basket = [{productId: 2, quantity:5}, {productId: 6, quantity: 4}, {productId: 4, quantity: 18}, {productId: 3, quantity: 5}]
将购物篮保存在localStorage中:
每当您需要更新此列表/数组时,请从localStorage获取basketContainer并循环遍历。
const update = JSON.parse(localStorage.getItem('basketContainer'))
update.forEach(x => {if (x.productId == 4) {x.quantity+=1}})
您现在可以控制更新,您会看到更改。
请同样对减量进行应用。
您可以创建类似以下的功能
const incrementDecrement = (list, action){ update.forEach(x => {if (x.productId == 4) {x.quantity`${action}`=1}})
}
// Where action is what determines if it is an increment(+) or decrement(-)
```
4. Once you're done, you can save the data back in your localStorage with the same initial name as it just overwrites the initial one.
something like this: ```localStorage.setItem('basketContainer', JSON.stringify(update))````
Goodluck!
By the way, you might want to read this: [stop_using_localStorage][1]
[1]: https://dev.to/rdegges/please-stop-using-local-storage-1i04
答案 1 :(得分:0)
我认为这是简单的方法
如果存储的数据是这样的{ ProductID: 241, Quantity: quantity }
//check if BasketContents exists
if(localStorage.BasketContents){
// if exists
let BasketContents = JSON.parse( localStorage.BasketContents );
// add 5 to productId
BasketContents.ProductID += 5;
// then update localstorage
localStorage.BasketContents = JSON.stringify(BasketContents);
}