简体   繁体   English

在localstorage中创建多项目JSON对象

[英]Creating multi-item JSON object in localstorage

I'm new to working with both JSON and localStorage. 我是同时使用JSON和localStorage的新手。

I am trying to create a small client-side "basket" of sorts which stores a productID in my localStorage under the title cart . 我正在尝试创建一个小的客户端“篮子”,该产品将productID存储在我的localStorage中标题为cart

At present, my cart localStorage item is overwritten with a new productID instead of having the productID added as a new item. 目前,我的cart localStorage项被新的productID覆盖,而不是将productID添加为新项。 Of course the cart object should be able to accept multiple items. 当然,购物车对象应该能够接受多个物品。

Here is my codepen: http://codepen.io/franhaselden/pen/regVgj 这是我的代码笔: http ://codepen.io/franhaselden/pen/regVgj

My addToCart function is really simple, but I'd not adding the right JSON structure. 我的addToCart函数确实很简单,但是我没有添加正确的JSON结构。 I'm confused over what the JSON structure should be in this case where multiple items are added but the key is the same ( productID ) 在添加了多个项目但键相同( productID )的情况下,我对JSON结构应该是什么感到困惑

function addToCart(productID) {
  localStorage.setItem('cart', JSON.stringify(productID));
}

Use an array: 使用数组:

function addToCart(productID) {
  // Get stored array, if it's not set, it should be set to an empty array
  var basket = localStorage.getItem('cart');
  basket = basket ? JSON.parse(basket) : [];

  basket.push(productID);
  localStorage.setItem('cart', JSON.stringify(basket));
}

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

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