简体   繁体   English

如何检查本地存储中是否已存在项目/值

[英]How to check if a item/value already exists in Local Storage

I am working on a shopping cart application were users can click an Add to Cart button that will then add the specific item to local storage. 我正在使用购物车应用程序,用户可以单击“添加到购物车”按钮,然后将特定项目添加到本地存储中。 When the user is adding a product to their shopping cart I need to be able to check to see if that specific item/value/product already exists in local storage. 当用户将产品添加到他们的购物车中时,我需要能够检查该特定项目/值/产品在本地存储中是否已经存在。 If it does, I need to increase only the count of that item/value/product by 1. If not, I need to add an entirely new item/value/product to local storage with a count of 1. 如果是这样,我只需要将该项目/值/产品的数量增加1。否则,我需要将一个全新的项目/值/产品的本地数量添加为1。

How can I find if an item already exists in local storage and compare it to the id of the current product that a user is attempting to add to their cart? 如何查找本地存储中是否已存在商品,并将其与用户试图添加到购物车中的当前产品的ID相比较? My first few attempts failed miserably and have yet to find anything online that is helping with this issue. 我的前几次尝试都失败了,但还没有找到任何可以解决此问题的在线方法。 Is there a better way of going about this? 有没有更好的方法来解决这个问题? Any assistance is appreciated. 任何帮助表示赞赏。 Even a good link to a good page would be extremely helpful. 即使是指向良好页面的良好链接也将非常有帮助。

Below is the code I have to attempt in checking for if the productid being added matches any of the productids in local storage. 下面是我必须尝试检查要添加的产品ID是否与本地存储中的任何产品ID相匹配的代码。 Basically if the productId that is being added matches the productId of an item in local storage simply add 1 to the quantity. 基本上,如果要添加的productId与本地存储中某个项目的productId相匹配,则只需在数量上加1。

var retrieverObject = localStorage.getItem('Products');
var retrieveObject = JSON.parse(retrieverObject);

var data = {};
var productId = currentNode.name;
var product = currentNode;

data.productPrice = product.parentNode.previousSibling.previousSibling.id;
data.productId = productId;

var length = retrieveObject.length;
console.log(length);
for(var i = 0; i<length; i++){
  if(retrieveObject[i].productId == data.productId){
    var quantity = retrieveObject[i].quantity;
        retrieveObject.push({"productPrice": data.productPrice, "productId": data.productId, "quantity": quantity++});
  }else{
        retrieveObject.push({"productPrice": data.productPrice, "productId": data.productId, "quantity": 1});
  }
}
console.log(retrieveObject);

localStorage.setItem('Products', JSON.stringify(retrieveObject));
var retrievedObject = localStorage.getItem('Products');
var obj = JSON.parse(retrieverObject);
var len = obj.length;
console.log(len);

  for(var i=0; i<len;i++){
    console.log(obj[i]['productPrice']+", "+obj[i]['productId']);
  }

} } }}

There are a few issues. 有几个问题。 First, I am not entirely certain that the productId of the retrieved object is being compared to the one that is being added. 首先,我不能完全确定是否将检索到的对象的productId与要添加的对象进行比较。 Secondly, the for(var i = 0; i<length; i++){} definitely does not seem to be doing what was expected and is multiplying the number of items being added by 2. Thirdly, which may relate to the second issue, the retrieveObject.push() is not updating the quantity of the product but is adding an entire new entry to local storage. 其次, for(var i = 0; i<length; i++){}似乎并没有达到预期的效果,而是将要添加的项数乘以2。第三,这可能与第二个问题有关, resolveObject.push()不会更新产品的数量,而是会向本地存储中添加一个全新的条目。 The given answers did not seem to be working for me before so this is what I have been working on. 给出的答案似乎对我没有帮助,所以这就是我一直在努力的事情。 Any new answers or general help would be great. 任何新的答案或一般帮助都很好。

PT 2. : So I am having an issue with the first entry into the local storage. PT 2 ::因此,我第一次进入本地存储设备时遇到问题。 Without noting that when there is nothing in local storage and you make a call to get the items in it, it returns null or undefined. 无需注意,当本地存储中没有任何内容并且您调用以获取其中的项目时,它返回null或未定义。 So currently I have it set up like this: 因此,目前我将其设置如下:

if(localStorage.getItem("Products") === null || localStorage.getItem("Products") === undefined){
  var data = {};
  var productId = currentNode.name;
  var product = currentNode;

  data.productPrice = product.parentNode.previousSibling.previousSibling.id;
  data.productId = productId;
  var obj = [];
  obj = obj[data.productId] = {
    productPrice: data.productPrice,
    count: 1
  };
  console.log(obj);
  localStorage.setItem('Products', JSON.stringify(obj));
}

else{
  var retrieverObject = localStorage.getItem('Products');
  var retrieveObject = JSON.parse(retrieverObject);

  var data = {};
  var productId = currentNode.name;
  var product = currentNode;

  data.productPrice = product.parentNode.previousSibling.previousSibling.id;
  data.productId = productId;

  if(retrieveObject[data.productId]){
    retrieveObject[data.productId].count++;
  }else{
    retrieveObject[data.productId] = {
      productPrice: data.productPrice,
      count: 1
};
  }
console.log(retrieveObject);
localStorage.setItem('Products', JSON.stringify(retrieveObject));
}

This creates a first entry in local storage that looks like this : {"productPrice":"78.34","count":1}, and then when adding others looks like this: {"productPrice":"78.34","count":1,"rJUg4uiGl":{"productPrice":"78.34","count":3}} and works perfectly fine. 这将在本地存储中创建第一个条目,如下所示:{“ productPrice”:“ 78.34”,“ count”:1},然后在添加其他条目时如下所示:{“ productPrice”:“ 78.34”,“ count” :1,“ rJUg4uiGl”:{“ productPrice”:“ 78.34”,“ count”:3}}并可以正常使用。 The issue is getting the first entry to b formatted properly. 问题是将第一个条目正确格式化为b。 When I change the code in the first if statement like so: 当我在第一个if语句中更改代码时,如下所示:

var obj = [];
      obj[data.productId] = {
        productPrice: data.productPrice,
        count: 1
      }

I get an empty [] in local storage but when I console.log the obj it is in the proper format. 我在本地存储中得到一个空的[],但是当我console.log obj时,它的格式正确。 [rJUg4uiGl: Object]. [rJUg4uiGl:对象]。 I have been stuck on this and haven't been able to get it working. 我一直在坚持这一点,但无法使其正常工作。 Again, any help would be really appreciated. 再次,任何帮助将不胜感激。

Once you have your data structure in obj , I would suggest using a dictionary with product IDs as keys. 一旦您在obj有了数据结构,我建议您使用带有产品ID作为键的字典。

To add the order or whatever, where you have: 要添加订单或其他任何您需要的位置:

obj.push({"productPrice": data.productPrice, "productId": data.productId});

Use: 采用:

if (obj[data.productId]) { // if the entry exists,
  // increment the count
  obj[data.productId].count++;
} else { // if it doesn't,
  // add a new entry with count = 1
  obj[data.productId] = {
    productPrice: data.productPrice,
    count: 1
  };
}

Here is a complete function, including localStorage handling: 这是一个完整的功能,包括localStorage处理:

function addToCart(productID, productPrice) {
  // get the current cart, or an empty object if null
  var cart = JSON.parse(localStorage.getItem("Products")) || {};

  // update the cart by adding an entry or incrementing an existing one
  if (cart[productId]) {
    cart[productId].count++;
  } else {
    cart[productId] = {
      productPrice, // shorthand for `productPrice: productPrice,`
      count: 1
    };
  }

  // put the result back in localStorage
  localStorage.setItem("Products", JSON.stringify(cart));
}

The solution above is preferable because you can check for a productId without looping through the whole list. 上面的解决方案是更可取的,因为您可以检查productId而不用遍历整个列表。 If you really want to keep your current data structure of an array of objects, you could update it like this: 如果您确实要保留对象数组的当前数据结构,则可以这样更新它:

var length = retrieveObject.length;
console.log(length);
for (var i = 0; i < length; i++) {
  if (retrieveObject[i].productId == data.productId) {
    retrieveObject[i].quantity++; // update the entry in the array
  } else {
    retrieveObject.push({
      productPrice: data.productPrice,
      productId: data.productId,
      quantity: 1
    });
  }
}

Note that you shouldn't push a new entry into the array; 请注意,您不应该push新条目push入数组。 just update the existing one. 只需更新现有的。

Assuming you are using localStorage node package you could do 假设您正在使用localStorage节点包,则可以执行

if (localStorage.getItem('Products') !== null) {
   localStorage.setItem('Products', JSON.stringify(obj));
}

Here is your reference: 这是您的参考:

https://www.npmjs.com/package/localStorage https://www.npmjs.com/package/localStorage

Regards 问候

Update: 更新:

Searching within your objet is a different story... so you want to check if the Product id is there then you can search for it using lodash 在对象中搜索是另一lodash ...所以您想检查一下产品编号是否存在,然后可以使用lodash搜索

var _ = require('lodash');
// the rest of your code to get the data.productId set

if (localStorage.getItem('Products') !== null) {
   var arrayOfProducts = localStorage.getItem('Products');
   var existingProducts = _.filter(arrayOfProducts, function (product) { return product.productId === data.productId });
   if (existingProducts.length > 0) {
      // product found, do your logic
   }
}

Here's lodash info https://www.npmjs.com/package/lodash 这是lodash信息https://www.npmjs.com/package/lodash

The other option is using a dictionary and having the productId as key and then using Object.keys to search for it... I've offered an approach that does not change your json structure. 另一个选择是使用字典并将productId作为key ,然后使用Object.keys进行搜索...我提供了一种不会更改json结构的方法。

Just use localstorage.getItem ; 只需使用localstorage.getItem ; it returns null if the key doesn't already exist. 如果键尚不存在,则返回null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM