javascript - alter array object property then save back to localStorage? -
i'm doing cart , want increment qty if item_id exising in localstorage.
<button data-item_id="1" data-item_name="cake" data-item_price="2 dollar">add cart</button>
not sure why below code doesn't work, added new object instead of increment qty value.
$(function(){ $('button').click(function(){ var item_id = $(this).attr('data-item_id'); var item_name = $(this).attr('data-item_name'); var item_price = $(this).attr('data-item_price'); var arr = json.parse(localstorage.getitem('cart')) || []; var obj = {}; if(arr.length === 0){ // first time insert obj.item_id = item_id; obj.item_name = item_name; obj.item_price = item_price; obj.item_qty = 1; }else{ $(arr,function(i){ //doesn't work here obj.item_qty[i] = parseint(this.qty) + 1; }); } arr.push(obj); localstorage.setitem('cart',json.stringify(arr)); }); });
debug few hours couldn't solved.
use {} instead of [] making arr
contain 1 object per item_id , each object 1 added qty each time called. there no remove in code
$(function(){ $('button').on("click",function(e){ var item_id = $(this).data("item_id"); var item_name = $(this).data("item_name"); var item_price = $(this).data("item_price"); var cart = json.parse(localstorage.getitem('cart')) || {}; var currentobj = cart[item_id]; if(currentobj){ currentobj.qty++; // increase qty 1 } else { // item_id had not been stored before, create cart[item_id]= { "item_name" :item_name, "item_price":item_price, "item_qty" :1 } } localstorage.setitem('cart',json.stringify(cart)); }); });
Comments
Post a Comment