I have this array and I’m trying to delete a site from it but it’s not working. I know the function is called because I have added an alert to it and it alerted.
I removed some functions from the post just to make it shorter. But I have one function that removes ites from the array and it works great. It’s just deleting a site by siteid that doesn’t work for some reason.
[
{
"siteId": "9843598",
"items": [
{
"catNum": 9418956196,
"title": "This is item 1",
"qty": 1
}
]
},
{
"siteId": "89419111",
"items": [
{
"catNum": 1231654351,
"title": "This is item 2",
"qty": 1
},
{
"catNum": 9418956196,
"title": "This is item 1",
"qty": 1
}
]
}
]
function deleteSite(quoteCart, siteId) {
try {
quoteCart = quoteCart.filter((site) => site.siteId !== siteId);
console.log("Filtered array:", quoteCart); // Check the filtered array
updateCartDisplay();
openWindowWithArrayContents();
}
catch (error) {
console.error("Error in deleteSite:", error);
}
}
If I pressed delete on site # 9843598 I would expect the
[
{
"siteId": "89419111",
"items": [
{
"catNum": 9418956196,
"title": "This is item 1",
"qty": 1
},
{
"catNum": 1231654351,
"title": "This is item 2",
"qty": 1
}
]
}
]
Playground
https://jsfiddle.net/Bigmuddyfoot/4v5w2nLa/
3
Answers
I think the
deleteSite
function might not be updating the cart properly due to a scoping issue. When you’re passingquoteCart
into thedeleteSite
function, the modifications made inside the function are limited to the local scope. So, you could return the updatedquoteCart
from thedeleteSite
function and use that returned value.Check the modified version:
And when calling the deleteSite function, update the quoteCart variable and refresh the display:
See this JS<>Fiddle