简体   繁体   中英

Creating multi-item JSON object in localstorage

I'm new to working with both JSON and localStorage.

I am trying to create a small client-side "basket" of sorts which stores a productID in my localStorage under the title cart .

At present, my cart localStorage item is overwritten with a new productID instead of having the productID added as a new item. Of course the cart object should be able to accept multiple items.

Here is my codepen: http://codepen.io/franhaselden/pen/regVgj

My addToCart function is really simple, but I'd not adding the right JSON structure. 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 )

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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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