I am currently making a simple cart with vue.js + sessionStorage. Here's my js code(vue.js method):
storeLocalStorage(){
var tempitem = store.getters.printCart;
if(tempitem.length){
if(sessionStorage.length){
var existingCart = JSON.parse(sessionStorage.cart);
var size = Object.keys(existingCart).length;
//console.log(existingCart);
const index = existingCart.findIndex(existingCart => existingCart.itemID === tempitem.itemID);
//console.log(index);
if (index === -1) {
existingCart.push(tempitem[0]);
} else {
existingCart[index].itemQuantity = existingCart[index].itemQuantity + tempitem.itemQuantity;
}
let myObj_serialized = JSON.stringify(existingCart);
sessionStorage.setItem('cart', myObj_serialized);
}
else {
let myObj_serialized = JSON.stringify(tempitem);
sessionStorage.setItem('cart', myObj_serialized);
}
}
}
And here's my Object Arrays:
TempItem:
{
itemID: "a1b1c1",
itemName: "sessionItem1",
itemPrice: 550,
itemQuantity: 1,
},
{
itemID: "a2b2c2",
itemName: "sessionItem2",
itemPrice: 550,
itemQuantity: 1,
}
sessionStorage items:
0:
itemID: "a1b1c1",
itemName: "sessionItem1",
itemPrice: 550,
itemQuantity: 1,
1:
itemID: "a3b3c3",
itemName: "sessionItem3",
itemPrice: 550,
itemQuantity: 1,
2:
itemID: "a2b2c2",
itemName: "sessionItem2",
itemPrice: 550,
itemQuantity: 1,
What I want to accomplish is whenever a tempitem object has the same ID with a sessionStorage item, their quantity would be summed up and passed to the sessionStorage Item, but if it doesn't, it will add another index in the sessionStorage. But what happens is, instead of adding both the quantities, it creates another index with the same item but different quantities.
0:
itemID: "a1b1c1",
itemName: "sessionItem1",
itemPrice: 550,
itemQuantity: 1,
1:
itemID: "a1b1c1",
itemName: "sessionItem1",
itemPrice: 550,
itemQuantity: 5,
How do i accomplish this?
You can use this logic to sum the quantities , rest all remains same. Loop over the new array items, check for the object in existing array , if it exists add the quantity else add the new object in the existing array.
var arr = [{
itemID: "a1b1c1",
itemName: "sessionItem1",
itemPrice: 550,
itemQuantity: 1,
},{
itemID: "a3b3c3",
itemName: "sessionItem3",
itemPrice: 550,
itemQuantity: 1},
{
itemID: "a2b2c2",
itemName: "sessionItem2",
itemPrice: 550,
itemQuantity: 1}];
// new items array
var newArr= [{
itemID: "a1b1c1",
itemName: "sessionItem1",
itemPrice: 550,
itemQuantity: 1},
{
itemID: "a1b1c1",
itemName: "sessionItem1",
itemPrice: 550,
itemQuantity: 5},
{
itemID: "a5b5c5",
itemName: "sessionItem1",
itemPrice: 550,
itemQuantity: 5}]
newArr.forEach(newEle => {
let obj = arr.find(ob => ob.itemID === newEle.itemID);
if(obj!==undefined){
obj.itemQuantity+=newEle.itemQuantity;
} else{
arr.push(newEle);
}
})
console.log(arr);