unable to remove an object from localStorage using its id - javascript

function removeLocalStorageHelper(item, pizzaId) {
console.log(item.productID);
console.log(pizzaId);
if (item.productID == pizzaId) {
console.log("Working fine");
localStorage.removeItem(item);
console.log(localStorage);
}
}
function removeFromLocalStorage(pizzaId) {
var locStore = JSON.parse(localStorage.getItem("selectedProduct"));
var cartRowContents = locStore.map((item) =>
removeLocalStorageHelper(item, pizzaId)
);
}
Whenever the user clicks on "Remove" button, removeFromLocalStorage() function is called which receives a number type variable pizzaId. Now, this pizzaId is stored in the localStorage and I want to remove the object associated with this pizzaId from my localStorage.
CONSOLE OUTPUT
Please help me to remove an object from localStorage using productID.

You can't directly remove an item from the stored array. For that you need to remove the intended element from array and insert again to localStorage like below. Otherwise it'll remove complete list from localStorage.
Note: You need to do the same wile adding new item to the localStorage.
function removeFromLocalStorage(pizzaId) {
var locStore = JSON.parse(localStorage.getItem("selectedProduct"));
var cartRowContents = locStore.filter((item) => item.productID !== pizzaId);
localStorage.setItem("selectedProduct", JSON.stringify(cartRowContents))
}

As I reivew your code, I see that you are retrieving the item from localStorage like this localStorage.getItem("selectedProduct") The question here is do you want to remove the entire locStore or just a part of it. Maybe locStore is a complex collection (array) from multiple products and not a single entity as this code hints
var cartRowContents = locStore.map((item) =>
removeLocalStorageHelper(item, pizzaId));
If this is the case you need to do something like this
var locStore = locStore.filter(function(item, index){
return item.productID != pizzaId;
});
Now you have a locStore collection without the item you want to remove and you have to save it back to localStorage like this
localStorage.setItem('selectedProduct', JSON.stringify(locStore));
Essentially you are overriding the old selectedProduct value in localStorage with a new one that does not contain the removed product.
If for some reason locStore is just a simple JSON object that you want to remove you can do this to delete it from localStorage
localStorage.removeItem('selectedProduct')

Well, if you just need to remove the selectedProduct, you can do it like this:
localStorage.removeItem("selectedProduct");

Related

Assign new name to object's key in an array of objects

In a Grid, records are fetched from API and displayed. It also has certain input fields, with text and date field. While inputting data for date its getting displayed two times, as seen in the console, the data from JSON is as est: 10/20/2022 but I want to display it as Establish: 10/20/2022. What modifications could be made in the code? Please refer to code below.
//Here 'allData' is an array of data from JSON
const tempData = allData;
tempData.map((x) => {
if (data.id === x.id) {
x.name = data.textVal;
}
// Here I'm trying to assign new key 'Establish' to old key 'est'
if (data.id === x.id) {
x["est"] = x["Establish"];
x.Establish = data.dateVal;
}
});
Please refer to codesandbox link --> https://codesandbox.io/s/jovial-aryabhata-95o2sy?file=/src/Table.js
Give this a whirl
if(data.id === x.id) {
delete Object.assign(x, {['Establish']: x['est'] })['est'];
}
I think your way works but if you want another way so you can create a new property by using:
Object.defineProperty(x, "Establish", Object.getOwnPropertyDescriptor(x, "est"));

UseState how to set an Array back to empty?

I'm trying set clickFavIconArray back to an empty array with the hook.
Basically, the setClickFavIconArray has a list of IDs the showFavIcon() checks that ID and if it contains the same ID I want to remove it from the array and update the setClickFavIconArray to the new Array.
However, it just seems to be adding on to the original clickFavIconArray no matter what. Is there a way to clear the clickFavIconArray state back to an [] empty array?
Some help here would be awesome.
const [clickFavIconArray, setClickFavIconArray] = useState([]);
function showFavIcon(id){
if (clickFavIconArray.includes(id)) {
const newArray = clickFavIconArray.filter(item => !id.includes(item))
setClickFavIconArray(newArray)
}
setClickFavIconArray([...clickFavIconArray, id])
}
Simply pass the new value of empty array to setClickFavIconArray():
setClickFavIconArray([])
To make sure that the id is not immediately added to the array again, add a return statement inside the if-statement.
const [clickFavIconArray, setClickFavIconArray] = useState([]);
function showFavIcon(id){
if (clickFavIconArray.includes(id)) {
const newArray = clickFavIconArray.filter(item => !id.includes(item));
setClickFavIconArray(newArray);
return; // make sure that the next line is not executed
}
setClickFavIconArray([...clickFavIconArray, id])
}
There are two issues with the code
filter function seems to be invalid it should be replaced with
clickFavIconArray.filter(item => id != item)
You are adding id again to the array with this
setClickFavIconArray([...clickFavIconArray, id])
If you want to remove id, there is no need for this line in your code.
However you can always set clickFavIconArray to an empty array state using this code:
setClickFavIconArray([])

How would I go about deleting a single item in Firebase?

How would I go about deleting just a single item?
Provided I know the 'name' value ("To add") but I don't know the item ID value (-M0qUq...).
The following code works to delete the item, but I want to make it dynamic and not have to hardcode in the ID value.
handleRemove = (item) => {
db.ref('/items/-M0qUPNnHRbZAb1R3690/').remove();
}
Try the following:
let query = db.ref('items').orderByChild("name").equalTo("To add");
db.once('value').then((snapshot) => {
snapshot.forEach((subSnapshot) => {
let key = subSnapshot.key;
db.ref('items').child(key).remove();
});
});
First add a query equalTo, then iterate inside the returned result to be able to retrieve the key and then use remove() to delete.

Add an object to JSON

I have a settings.json file that contains following data (where 123456789 is a distinct user id):
{
"123456789":
{"button_mode":true}
}
So what I need to do is push a similar id: {button_mode: value} object to this JSON file in case there's no entry for current user's id. I tried to use lcSettings.push() but obviously it did not work since I have an object, not an array. When I put square brackets instead of curly ones to make it an array, my code doesn't do anything at all.
Here's a snippet of it (Node.js):
var lcSettings = JSON.parse(fs.readFileSync('./settings.json', 'utf8'));
var currentUser = id;
if (lcSettings.hasOwnProperty(currentUser)) {
// in case settings.json contains current user's id check for button_mode state
if (lcSettings[currentUser].button_mode == true) {
// if button_mode is on
} else
if (lcSettings[currentUser].button_mode == false) {
// if button_mode is off
}
} else {
// in case there's no entry for current user's id
// here's where I need to push the object for new user.
}
fs.writeFileSync('./settings.json', JSON.stringify(lcSettings))
Does anybody have ideas on how it can be implemented? Any help appreciated.
You can use bracket notation to add a dynamic property to an object:
lcSettings[id] = { button_mode: false };
You may also want to verify that settings.json is not empty otherwise the JSON.parse() will fail. In this case, you would want to initialize lcSettings to an empty object (lcSettings = {}) so the above will work.
To 'push' elements to an object you simply define them, as in
object['123456789'] = { button_mode: true };

Delete Session Storage - Shopping Cart Project

I hope this is a good question. I am working on a shopping cart project. I have been scouring the internet through different tutorials on shopping carts. I am attempting to write mine in Vanilla Javascript. I am having a problem with removing shopping cart items from session storage.
Below is what is currently in my session storage. As you can see it is an Array of objects.
[{"id":"8","name":"Candy
Skull","price":"20000","image":"../images/candyskull-
min.JPG","qty":"1"},{"id":"5","name":"Upsidedown
House","price":"20000","image":"../images/upsidedownhouse-
min.JPG","qty":"1"},{"id":"6","name":"Brooklyn
Window","price":"30000","image":"../images/brooklynwindow-
min.JPG","qty":"1"},{"id":"4","name":"Hand That
Feeds","price":"40000","image":"../images/handthatfeeds-
min.JPG","qty":"1"}]
I want to loop through the array and remove the matching object from the cart storage.
Below is the JS Code used to generate the .remove-from-cart buttons. As you can see it includes all the dataset information.
<td>
<span class="remove-from-cart">
<b data-id="${value.id}" data-name="${value.name}" data-
price="${value.price}" data-image="${value.image}" data-
qty="${value.qty}">X</b>
</span>
</td>
To test the functionality of what I have done so far you can visit www.dancruzstudio.com/shop
The function that I can't get to work properly is the removeFromStorage() function. For some reason when comparing an object to the objects in the array I'm never getting back a true boolean value, even when there are items in the cart that should match. Where am I going wrong? I hope someone can help. Below is a copy of my JS code.
The method I am using is having an identical dataset value in the remove item button generated by JS and then parsing that dataset into an object and comparing it to the objects in the session storage array which is called shopItems inside the removeFromStorage() function. I hope this information is enough for someone to see my problem. Thank you in advance.
// Remove item from DOM
document.querySelector('#cart-list').addEventListener('click',
removeFromCart)
function removeFromCart(e) {
if(e.target.parentElement.classList.contains('remove-from-cart')) {
//Remove from DOM
e.target.parentElement.parentElement.parentElement.remove();
//Remove from Session Storage
removeFromStorage(e.target.dataset);
}
}
// remove from Session storage
function removeFromStorage(removedItem){
let shopItems;
if(sessionStorage['sc'] == null){
shopItems = [];
} else {
shopItems = JSON.parse(sessionStorage['sc'].toString());
}
var compare = JSON.parse(JSON.stringify(removedItem))
shopItems.forEach(function(item, index){
if(compare === item){
console.log(compare);
console.log(item);
// shopItems.splice(index, 1);
}
});
sessionStorage['sc'] = JSON.stringify(shopItems);
}
You can not compare objects like this.
let a = {p:1};
let b = {p:1};
console.log(`a ===b ? ${a===b}`);
If your objects are fairly simple you can try comparing their stringify representation:
let a = {p:1};
let b = {p:1};
const compare = (x,y) => {
return JSON.stringify(x) === JSON.stringify(y);
}
console.log(`a === b ? ${compare(a,b)}`);
or write your custom compare function (that may be challenging):
Compare JavaScript objects
Since your objects are decorated with an id, the easisest way would be to idntify them by that:
let storage = [{"id":"8","name":"Candy Skull", "price":"20000","image":"../images/candyskull- min.JPG","qty":"1"},{"id":"5","name":"Upsidedown House","price":"20000","image":"../images/upsidedownhouse- min.JPG","qty":"1"},{"id":"6","name":"Brooklyn Window","price":"30000","image":"../images/brooklynwindow- min.JPG","qty":"1"},{"id":"4","name":"Hand That Feeds","price":"40000","image":"../images/handthatfeeds- min.JPG","qty":"1"}];
let items = [{"id":"6","name":"Brooklyn Window","price":"30000","image":"../images/brooklynwindow- min.JPG","qty":"1"}, {"id":"5","name":"Upsidedown House","price":"20000","image":"../images/upsidedownhouse- min.JPG","qty":"1"}];
const pluck = (acc, crt) => {
acc.push(crt.id);
return acc;
};
let storageIndexes = storage.reduce(pluck, []);
let itemsIndexes = items.reduce(pluck, []);
let removeIndexes = [];
itemsIndexes.forEach(id => removeIndexes.push(storageIndexes.indexOf(id)));
console.log('storage', storage);
console.log('removed items', items);
removeIndexes.sort().reverse().forEach(index => storage.splice(index,1));
console.log('remaining storage', storage);

Categories

Resources