Problem conditions if and else if in a for loop adding quantity in object in array or new object in array not working why?

Viewed 47

my problem is that in my if and else if condition of the for loop the first condition is triggered if we add the second same product contained in the table but when the color condition of the product changes and that lid and the same it triggers me two conditions for the click on the product. What to do ?

I would like to add a quantity ++ if the object and already in the table if the id and the color selected in the input are the same. otherwise you add a new object in the table. After the problem is that it adds both the quantity in the product and the quantity in the object here is my code and some screenshot of the console below

produitData = product choice on the page of product

produitTableau = Array an objects save in the localStorage

select = the input contained the varnish value

const addBasket = () => {
  let bouton = document.getElementById(produitData._id);
  bouton.addEventListener("click", () => {
    let produitTableau = JSON.parse(localStorage.getItem("produit"));
    let select = document.getElementById("vernis");

    const fusionProduitTeinte = Object.assign({}, produitData, {
      teinte: `${select.value}`,
      quantite: 1,
    });

    if (produitTableau == null) {
      produitTableau = [];
      produitTableau.push(fusionProduitTeinte);
      localStorage.setItem("produit", JSON.stringify(produitTableau));
    } else {
      for (i = 0; i < produitTableau.length; i++) {
        if (
          produitTableau[i]._id == produitData._id &&
          produitTableau[i].teinte == select.value
        ) {
          produitTableau[i].quantite++;
          console.log("quantite ++");
          localStorage.setItem("produit", JSON.stringify(produitTableau));
        } else {
          console.log("nouveau");
          produitTableau.push(fusionProduitTeinte);
          localStorage.setItem("produit", JSON.stringify(produitTableau));
        }
      }
    }

 

    console.log(select.value);
    console.log(produitTableau);

    // window.location = "panier.html";
  });
  return;
};

one click one object add to array second click quantity++ add in object to the array it's work the fisrt conditions enter image description here

third click quantity++ add in object to the array it's work the fisrt conditions enter image description here

four click im changed the select value but the product id is the same as in the object in the table quantity++ add in object to the array and new object for the same time it's not work conditions and continue to add new object in the array for the different value and add quantity++ in the infinity

enter image description here

what's the solution is for the good conditions in my code function?

0 Answers
Related