Currently, I'm working on a function to store details of a couch in a JS object with 3 properties locally. The properties include:
An ID (obtained from the product URL using a function)
A color (retrieved through an event listener)
A quantity (also obtained through an event listener)
I already have a function that allows me to store objects locally using an array:
function addedToCart(productObject) {
let listOfProducts = getProducts();
listOfProducts.push(productObject);
registerProducts(listOfProducts);
}
function getProducts() {
let listOfProducts = localStorage.getItem("listOfProducts");
if (listOfProducts == null) {
return [];
} else {
return JSON.parse(listOfProducts);
}
}
function registerProducts(listOfProducts) {
localStorage.setItem("listOfProducts", JSON.stringify(listOfProducts));
}
In addition to this, I have implemented 3 event listeners:
- To detect when the user selects a color option and capture its value
- To track changes in the input field for quantity and retrieve its value
- To respond to the user clicking on the "Add to cart" button
Below is my JavaScript code:
... (JavaScript code omitted for brevity) ...The issue I am facing is that redundant object instances are added to the array when the user clicks the "Add to cart" button multiple times or changes the quantity before adding to the cart.
[{id: "107fb5b75607497b96722bda5b504926", color: "White", quantity: "1"},…]
0: {id: "107fb5b75607497b96722bda5b504926", color: "White", quantity: "1"}
1: {id: "107fb5b75607497b96722bda5b504926", color: "Blue", quantity: "1"}
2: {id: "107fb5b75607497b96722bda5b504926", color: "Blue", quantity: "1"}
3: {id: "107fb5b75607497b96722bda5b504926", color: "Blue", quantity: "2"}
My aim now is to devise a function to compare and eliminate redundant objects in the array based on the ID, color, and quantity properties. This function should follow specific conditions outlined above.
If you need further clarification or have any suggestions regarding my code, please feel free to share. Your assistance is greatly appreciated.