alter array object property then save back to loca

2019-08-10 15:19发布

问题:

I'm doing a cart and I want to increment the qty if the item_id exising in localStorage.

<button data-item_id="1" data-item_name="cake" data-item_price="2 dollar">Add to cart</button>

Not sure why my below code doesn't work, it added a new object instead of increment the 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 for few hours couldn't solved.

回答1:

Use {} instead of [] making the arr contain one object per item_id and each object will get 1 added to the qty each time it is called. There is no remove in this 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 the qty by one
       }
       else { // item_id had not been stored before, create it
         cart[item_id]= { 
           "item_name" :item_name,
           "item_price":item_price,
           "item_qty"  :1
         }
       }
       localStorage.setItem('cart',JSON.stringify(cart));
    });
});


回答2:

Then you have to do like this:

$(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 = {};
            obj.item_id = item_id;
            obj.item_name = item_name;
            obj.item_price = item_price;

            obj.item_qty = 1;
            detectchange = 'no';

            $.each(arr,function(i){
            if(this.item_id == obj.item_id){
               this.item_qty = parseInt(this.item_qty) + 1; detectchange = 'yes';     }
            });
        if(detectchange =='no'){ 

        arr.push(obj); }
        localStorage.setItem('cart',JSON.stringify(arr));

    });

});