简体   繁体   中英

how to update array obj in localStorage if item is already exist

Wondering how to update array obj in localStorage when an item is already exist, my localStorage create a new array after refresh rather than updating or adding new obj.

localStorage obj --

cart - [{"Product":"Coke","Price":"1.99","Quantity":"1x "}]

addToCart function where I add I push the object to array[]

var itemStorage = [];
for (var key in drinkCounter) {
...

        var cartObj = { Product: key, Price: drinkCounter[key].price, Quantity: drinkCounter[key].count + 'x ' }
        itemStorage.push(cartObj);
        localStorage.setItem('cart', JSON.stringify(itemStorage));
...

    }

Here's a JSfiddle , so once you added an item and refresh the page and add the same or new item it recreates the localStorage , how can I update it instead of recreating a new one everytime you refresh the page?

Edit -- if you added the same item it should update the {Quantity:}

Following the answer below, I tried updating item quantity of the existing item however that didn't work. Any suggestion?

cartItems.forEach(function (item, i) {
            if (item.Product == key) {
                item.Quantity = drinkCounter[key].count;
                // item.Quantity += 1; // or no avail
                index = i;
            }
        });

Fixed localStorage quantity count

if (index !== -1) {
  cartItems[index].Quantity = parseInt(cartItems[index].Quantity) + 1 + 'x';
} else {
  var cartObj = { Product: key, Price: drinkCounter[key].price, Quantity: drinkCounter[key].count + 'x ' }
  cartItems.push(cartObj);
}

**Edit -- ** Quick question about total price, can someone point out why when I add an item the totalPrice is 0 when it should be the item price

You can't avoid stringifying localStorage data.

var data = JSON.parse( localStorage.getItem('cart') );
for (var key in drinkCounter) {
...       

    // search for a product with current key
    var index = -1;
    data.forEach(function(item, i){
        if( item.Product === key ) {
            index = i;
        }
    });

    if (index !== -1) {
        // data[index] = cartObj;
        data[index].Quantity = parseInt(data[index].Quantity.split(x)[0]) + drinkCounter[key].count + 'x ';
    } else {
        var cartObj = { Product: key, Price: drinkCounter[key].price, Quantity: drinkCounter[key].count + 'x ' };
        data.push(cartObj);
    }
...
}

localStorage.setItem('cart', JSON.stringify(data));

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