Please help me to find a solution and a bit with my code refactoring.
I just want to put some objects from one array to a new and it will be like a product cart. That's why I don't want to see any duplicates but just: product - quantity in the modal window. I've got two arrays:
state = {
existData: [
{
productName: "CoolProductName 1",
count: 0,
image: "src.jpeg",
author: "Name Surname",
date: "21.02.2020",
id: 1,
},
{
productName: `CoolProductName 2"`,
count: 0,
image: "src.png",
author: "Name Surname",
date: "21.02.2020",
id: 2,
},
],
addedToCart: [],
};
So, the function is:
added = (id) => {
//get product Id from other component
this.setState(({ addedToCart, existData }) => {
let newObj = existData.filter((el) => el.id === id); // there is I get product selected by user from array of all products
return {
addedToCart: [...addedToCart, ...newObj],
};
});
};
With my little knowledge I thought to do something like:
let newObj = existData
.filter((el) => el.id === id)
.map((el) => {
if (el.count >= 0) {
el.count++;
}
return { ...el };
});
yes it returns value with the count++ but in addedToCart array I've got duplicates objects with different counts.
I see two ways:
- remove duplicates in
addedToCartarray after add an object to the cart and increase count then just show something like{addedToCart.prductName} - {addedToCart.count}in the cart. - count duplicate objects and remove count field.
What is the better way and suitable code? Thank you