Reputation: 655
I am creating an ordering system which a user will select an item and add them to cart. I use local storage to save the items selected and get those items on the next page.
What I wanted to do now is to update the stored data if the user selected the same item.
For example I have already stored
[{
"id": "1",
"name": "soap A",
"quantity": "10",
"price" : "50.00"
},
{
"id": "2",
"name": "soap X",
"quantity": "10",
"price" : "50.00"
}]
and the user again selected the the item with an id
of 1
(which is "soap A"
) and the quantity is "15"
, my current result looks like this
[{
"id": "1",
"name": "soap A",
"quantity": "10",
"price" : "50.00"
},
{
"id": "2",
"name": "soap X",
"quantity": "10",
"price" : "50.00"
},
{
"id": "1",
"name": "soap A",
"quantity": "15",
"price" : "50.00"
}]
What I wanted to do is to update if an object with the same ID exists on my local storage. it would look like this
[{
"id": "1",
"name": "soap A",
"quantity": "25",
"price" : "50.00"
},
{
"id": "2",
"name": "soap X",
"quantity": "10",
"price" : "50.00"
}]
and here is my script for inserting to local storage.
var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || [];
var newItem = {
'id' : $('#itemId').val(),
'name': $('#productName').val(),
'quantity': $('#quantity').val(),
'price': $('#productPrice').val(),
};
oldItems.push(newItem);
localStorage.setItem('itemsArray', JSON.stringify(oldItems));
Upvotes: 1
Views: 2383
Reputation: 371108
You need to find
a matching id
in the current array, if it exists. If so, assign to that element - otherwise, push a new element.
const oldItems = JSON.parse(localStorage.getItem('itemsArray')) || [];
const idToUse = $('#itemId').val();
const existingItem = oldItems.find(({ id }) => id === idToUse);
if (existingItem) {
Object.assign(existingItem, {
'name': $('#productName').val(),
'quantity': existingItem.quantity + $('#quantity').val(),
'price': $('#productPrice').val(),
})
} else {
const newItem = {
'id' : idToUse,
'name': $('#productName').val(),
'quantity': $('#quantity').val(),
'price': $('#productPrice').val(),
};
oldItems.push(newItem);
}
localStorage.setItem('itemsArray', JSON.stringify(oldItems));
Upvotes: 5