Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

421
Vistas
JavaScript: elimine el producto del carrito con el botón menos

Estoy intentando eliminar el producto añadido al carrito con el botón "-" cuando la cantidad llega a 1 unidad. Espero que alguien me pueda ayudar, llevo dos días buscando una solución. Gracias por adelantado.

 //changeNumber function changeNumber(action, id){ cart = cart.map((item)=> { let = oldNumber = item.numberOfUnits; if(item.id === id){ if (action === "meno" && item.numberOfUnits >1) { oldNumber-- } else if (action === "piu") { oldNumber++ } if (action === "meno" && item.numberOfUnits === 1){ console.log("delete") console.log(cart.splice(item.id, 1)); } updateCart(); } return { ...item, numberOfUnits: oldNumber, } }); updateCart(); }
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

La función de mapa no le permitirá eliminar elementos mientras está en bucle.

Hay dos enfoques:

  1. Guarde el índice de lo que desea eliminar y luego, después de .map (), llame a delete cart[index]
  2. Use una técnica diferente para actualizar la lista de carritos (recomendado)

Técnica #1

 function changeNumber(action, id) { var toRemove = null; var index = 0; [...] // Instead of the two console.logs toRemove = index; [...] // At the end of the map lambda index++; [...] // At the end of the changeNumber function if (toRemove !== null) delete cart[toRemove]; }

Técnica #2

En lugar de una matriz, use un objeto {id: item} . Esto le permite acceder y modificar un elemento específico sin tener que recorrerlo todo.

 var cart = {}; function addToCart(item) { if (item.id in cart) // Check if the item is already in the cart cart[item.id].numberOfUnits++; else { cart[item.id] = item; // You may want to copy the item instead of directly adding it item.numberOfUnits = 1; // May be unnecessary or unwanted, depending on your system } } function removeFromCart(item) { if (!(item.id in cart)) // If the item is already not in the cart return false; // The removal was already done cart[item.id].numberOfUnits--; if (cart[item.id].numberOfUnits <= 0) // The less-than is unnecessary, but a good check anyway delete cart[item.id]; return true; // The removal was successful } // Example addToCart({id: 5}); addToCart({id: 5}); addToCart({id: 7}); console.log(removeFromCart({id: 5})); // True; there was an item to remove console.log(removeFromCart({id: 7})); // True; there was an item to remove console.log(removeFromCart({id: 7})); // False; there was no item console.log(cart);

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda