Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

85
Visualizações
Update quantity of items in cart without pushing entirety of object in JS

I'm having a bit of trouble with this problem. I'm working on the project of an e-commerce application that works on several html pages. I managed to push products through the cart html page, but I can't seem to find a way to update on this page only the quantity of a product and not push every elements of said product (images, id, etc). Onclick, if product exists, I only want quantity to be updated. Here's the code if any of you can help me out that'd be greatly appreciated.

setItems(kanap);

function setItems(kanap) {

  let cart = JSON.parse(localStorage.getItem('cart'));

  let imgKanap = kanap.imageUrl;
  let idKanap = kanap._id;
  let colorKanap = colors.value;
  let quantityKanap = parseInt(quantity.value);
  let key = idKanap + ' ' + colorKanap;

  let cartItem = {
    id: idKanap,
    color: colorKanap,
    quantity: quantityKanap,
    kanap: kanap
  };

  if (cart === null) {
    cart = [];
  }

  cart.push(cartItem);

  localStorage.setItem('cart', JSON.stringify(cart));

  function addProduct(cartItem) {
    var found = false;
    for (key in cartItem) {
      if (cartItem[key].idKanap == idKanap) {
        cartItem[key].quantityKanap += quantityKanap;
        found = true;
        break;
      }
    }
    if (!found) {
      cart.push(cartItem);
    }
  }
  addProduct();
}
<div class="item__content__addButton">
  <button id="addToCart" type="submit">Ajouter au panier</button>
</div>

<section class="cart">
  <!-- <section id="cart__items">
         <article class="cart__item" data-id="{product-ID}">
            <div class="cart__item__img">
              <img id ="image" alt="Photographie dun canapé">
            </div>
            <div class="cart__item__content">
              <div class="cart__item__content__titlePrice">
                <h2 class=title></h2>
                <p class =price></p>
              </div>
              <div class="cart__item__content__settings">
                <div class="cart__item__content__settings__quantity">
                  <p class= quantity>Qté : </p>
                  <input type="number" class="itemQuantity" name="itemQuantity" min="1" max="100" value="">
                </div>
                <div class="cart__item__content__settings__delete">
                  <p class="deleteItem">Supprimer</p>
                </div>
              </div>
            </div>
        </article> -->
</section>

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

There's a few approaches you can take, but I am using .find to look through your cart.

If the .find() function finds an item with the same id as you're about to add, it will up the quantity of the existing item instead of appending another object with the same ID.

I used a mock local storage since local storage doesn't work in these snippets so just ignore that and use what you've been doing for local storage access.

let mockLS = null;

// guessed at the structure here, you may have something slightly different
const exampleItem = {
  _id: "abc",
  imageUrl: "imageurlexample",
  colors: {
    value: "red"
  },
  quantity: {
    value: 1
  }
}

const exampleItem2 = {
  _id: "abc2",
  imageUrl: "imageurlexample2",
  colors: {
    value: "blue"
  },
  quantity: {
    value: 1
  }
}

function setItems(kanap) {

  //let cart = JSON.parse(localStorage.getItem('cart'));

  // using a mock localstorage here since it doesn't work within this snippet, use what you currently have instead
  let cart = mockLS;

  let imgKanap = kanap.imageUrl;
  let idKanap = kanap._id;
  let colorKanap = kanap.colors.value;
  let quantityKanap = parseInt(kanap.quantity.value);
  let key = idKanap + ' ' + colorKanap;

  let cartItem = {
    id: idKanap,
    color: colorKanap,
    quantity: quantityKanap
    //kanap: kanap not sure why you want the whole obj here so I left this one out
  };

  if (cart === null) {
    cart = [];
  }

  // here is the case where cart exists and there may be the same item in it
  const itemExists = cart.find(item => {
    if(item.id === idKanap) {
      item.quantity += quantityKanap;
      return true;
    }
    return false;
  })

  if (!itemExists) {
    cart.push(cartItem);
  }

  //localStorage.setItem('cart', JSON.stringify(cart));
  mockLS = cart;
}

setItems(exampleItem);
setItems(exampleItem2);
setItems(exampleItem);

console.log(mockLS)

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda