【问题标题】:How to access a particular element in localStorage?如何访问 localStorage 中的特定元素?
【发布时间】:2019-07-15 09:54:28
【问题描述】:

我正在制作一个购物网站。我有一个具有唯一 ID、不同规格和数量的产品列表。我有一个 JSON,它看起来像这样:

{    
            "ProductId" : "1",
            "ProductCode" : "",
            "ProductName" : "XYZ",
            "Specifications" : {
                "Size" : ["S","M","L","XL","XXL"],
                "GrossWeight" : "200gm each",
                "Colour" : ["Beige"]
            },
            "SellingPrice" : 80,
            "MinimumOrderQuantity" : "1",
            "MaximumOrderQuantity" : "1",
            "ShippingCharges" : "75",
            }

有些产品的数量不超过1。如果用户在我的表中添加了一个只有1个数量的产品,我想阻止用户再次添加相同的产品已存在于购物车中。我正在使用localStorage 在按钮单击时保存产品。

这是我的代码:

if(localStorage.getItem("productTable") != null)
   {
      productTable = JSON.parse(localStorage["productTable"]);
      for(var x in productTable) {
          serialNumber++; 
   }
    productTable[serialNumber]={
            serialNumber: serialNumber, 
            ProductId : Id, 
            Colour : selectedColour, 
            Size : selectedSize, 
            QuantityAdded : selectedQuantity
          };
      }
     else {
            productTable[serialNumber]={
            serialNumber: serialNumber, 
            ProductId : Id, 
            Colour : selectedColour, 
            Size : selectedSize, 
            QuantityAdded : selectedQuantity
          };
      }

更新:我正在使用LocalStorage,当我添加一个项目时,它看起来像这样:

{serialNumber: 1, ProductId: "5", Colour: "Grey", Size: "N/A", QuantityAdded: "1"}

我可以将产品添加到购物车中。如何阻止用户再次添加相同的产品?

【问题讨论】:

    标签: javascript angularjs local-storage


    【解决方案1】:
    let product = {product_id: 1, ....}
    // make an entry in local storage using product id which will be unique
    // so in any case if local storage has product id as key available, do 
    // not add 
    if (product.quantity > 1 || !localStorage.getItem(product.product_id)) 
    {
        localStorage.setItem[product.product_id] = product;
    }else {
        // update login
    } 
    

    【讨论】:

    • 虽然此代码可能会解决问题,但 including an explanation 关于如何以及为什么解决问题将真正有助于提高您的帖子质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提出问题的人。请edit您的答案添加解释,并说明适用的限制和假设。
    【解决方案2】:
       if (localStorage.getItem("productTable") != null) {
          productTable = JSON.parse(localStorage["productTable"]);
          for (var x in productTable) {
              serialNumber++; 
          }
          if (selectedQuantity >= 1 && productTable[serialNumber].MaximumOrderQuantity == 1) {
            alert("Please don't add more than one of these items");
            return;
          }
        }
    
        productTable[serialNumber] = {
          serialNumber: serialNumber, 
          ProductId: Id, 
          Colour: selectedColour, 
          Size: selectedSize, 
          QuantityAdded: selectedQuantity
        };
    

    【讨论】:

    • 嗨@MarcoS,谢谢您的回复。我尝试了这段代码,但它给了我一个错误:MaximumOrderQuantity 未定义。
    • 这意味着您的 JSON 数据不符合您在问题中指定的格式...
    【解决方案3】:

    这里的问题是您正在根据serial number 的递增值设置地图中的产品,因为您使用的序列号对于相同的产品可能不同,因为您只有一个选项来确定是否该产品已添加到您的地图中,即遍历 productTable 中的所有值并检查产品 ID 并在将其添加到表之前进行检查。 assuming productTable is a map:

    productTable.forEach((productItem: Product, key: any) => {
        if(productItem.Id === Id){
        //this product is already there check for maximum quantity
        if(productItem.MaximumQuantity <= 1){
        //there is just 1 possible item so don't add it
        }else{
          // there is still space to add then proceed with adding the product
        }
    });

    【讨论】:

    • 嗨@Thriller,谢谢你的回复。我尝试了你的代码,但我得到一个错误,这种方法适用于 .ts 而不是 .js。你能把这个写成.js吗?
    • 我相信在JS中做到这一点的方法是for (var key in productTable) { var productItem = productTable[key]; if(productItem.Id === Id){ //this product is already there check for maximum quantity if(productItem.MaximumQuantity &lt;= 1){ //there is just 1 possible item so don't add it }else{ // there is still space to add then proceed with adding the product } }
    • 嗨@Thriller,您能在github.com/pradhanadi/Webiste 上查看我的代码并告诉我哪里做错了吗?
    【解决方案4】:

    我假设serialNumber 是特定Id 的产品计数

    const data = [{
      "ProductId": "1",
      "ProductCode": "",
      "ProductName": "XYZ",
      "Specifications": {
        "Size": ["S", "M", "L", "XL", "XXL"],
        "GrossWeight": "200gm each",
        "Colour": ["Beige"]
      },
      "SellingPrice": 80,
      "MinimumOrderQuantity": "1",
      "MaximumOrderQuantity": "1",
      "ShippingCharges": "75",
    }];
    const newProduct = {"ProductId": 1, MaximumOrderQuantity: 1};
    
    const products = data.filter(({ProductId})=>ProductId===newProduct.ProductId);
    
    if(newProduct.MaximumOrderQuantity >= products.length){
      //can't add product because already a maximum amount exists
      console.log("Maximum quantity already attained");
    } else {
      data.push(newProduct);
    }
    
    const res = JSON.stringify(data);
    
    console.log(res);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-09
      • 1970-01-01
      • 2011-08-16
      • 2016-07-05
      • 2018-07-05
      • 2015-06-07
      • 2013-03-24
      相关资源
      最近更新 更多