0

I'm trying to create an object with an array of multiple objects inside it, each inner-object representing a card.

I initialise all three outside of a forEach() loop, push each item into the array and then assign that array to a key in my outer-object:

const cart = {};
const cartItems = [];
const cartItem = {}

cart['cart-items'] = cartItems;

cartItems.push(cartItem); 

Inside the forEach() I take the card data, every time that cards button is clicked, and assign it to the inner-object:

///forEach() with 'click' event-handler for the buttons...

if (cartItem.id !== currentCardId) {
  cartItem['id'] = currentCardId;
  cartItem['name'] = currentCardName;
  cartItem['price'] = this.dataset.cardPrice;
  cartItem['quantity'] = 1;
} else {
  cartItem.quantity = cartItem.quantity + 1;
}

///...end of forEach()

This increments the 'quantity' of the 'card' if I click the same button multiple times, but when I click on a separate button it overwrites the existing card and it's 'quantity' value.

I understand if I initialise cartItem and cartItems inside the loop it prevents this overwriting, but then the cards 'quantity' doesn't increment, it just creates a separate object with a 'quantity' of '1'.

Any idea how I can work around this?

Edit

Complete code:

addCartBtn.forEach(i => {
  i.addEventListener('click', function(e) {
    let currentCardId = this.dataset.cardId;
    let currentCardName = this.dataset.cardName;
    let currentCardQuantity = 0;
    let currentCardPrice;

    let removeCartItem = document.getElementsByClassName('remove-cart-item');

    if (cartItem.id !== currentCardId) {
      cartItem['id'] = currentCardId;
      cartItem['name'] = currentCardName;
      cartItem['price'] = this.dataset.cardPrice;
      cartItem['quantity'] = 1;
    } else {
      cartItem.quantity = cartItem.quantity + 1;
    }

    if (this.dataset.cardPrice >= 1) {
      currentCardPrice = '£' + this.dataset.cardPrice;
    } else {
      currentCardPrice = this.dataset.cardPrice + 'p';
    }

    if (currentCardName.length > 10) {
      currentCardName = currentCardName.substring(0, 9) + '...';
    }

    if (document.getElementById(`${currentCardId}`)) {
      cartItems.forEach(i => {
        if (currentCardId === i) {
          currentCardQuantity += 1;
          document.getElementById(
            `${currentCardId}`
          ).innerHTML = `x${currentCardQuantity}`;
        } else {
          document.getElementById(`${currentCardId}`).innerHTML = 'x1';
        }
      });
    } else {
      dropdownCheckoutContainer.innerHTML += `<div class="dropdown-card" id="remove-${currentCardId}"><div class="dropdown-card-display"><p class="remove-${currentCardId}"><i class="fa fa-minus-square remove-cart-item" data-remove-id="${currentCardId}"></i>${currentCardName}</p></div><div class="dropdown-quantity"><p class="remove-${currentCardId}" id="${currentCardId}">x1</p></div><div class="dropdown-price"><p class="remove-${currentCardId}">${currentCardPrice}</p></div><div class="dropdown-hidden-id"><input class="remove-${currentCardId}" type="hidden" name="${currentCardId}" data-remove-id="${currentCardId}"></div></div>`;
    }

    if (dropdownCheckoutContainer.childElementCount >= 7) {
      dropdownCheckoutContainer.style.overflow = 'scroll';
      dropdownCheckoutContainer.style.borderBottom =
        '1px solid rgba(255, 98, 0, 0.5)';
    }

    if (dropdownCheckoutContainer.childElementCount > 1) {
      notificationIconContainer.style.display = 'flex';
      notificationIcon.innerHTML =
        dropdownCheckoutContainer.childElementCount - 1;
    }

    for (const i of removeCartItem) {
      i.addEventListener('click', function(e) {
        let btnId = this.dataset.removeId;
        let currentRow = document.getElementById(`remove-${btnId}`);
        let idIndexes = [];

        if (dropdownCheckoutContainer.childElementCount > 1) {
          dropdownCheckoutContainer.removeChild(currentRow);
        }

        notificationIcon.innerHTML = notificationIcon.innerText - 1;

        if (!(dropdownCheckoutContainer.childElementCount >= 7)) {
          dropdownCheckoutContainer.style.borderBottom = 'none';
          if (checkoutFull.childElementCount === 1) {
            checkoutFull.innerHTML = '';
          }
        }

        cartItems.forEach(i => {
          if (i === btnId) {
            idIndexes.push(cartItems.indexOf(i));
          }
        });

        for (let i = idIndexes.length - 1; i >= 0; i--) {
          cartItems.splice(idIndexes[i], 1);
        }
      });

      i.addEventListener('mouseup', () => {
        if (dropdownCheckoutContainer.childElementCount <= 2) {
          document.getElementById('empty-cart').style.display = 'block';
          checkoutLink.classList.add('checkout-link-disabled');
        }

        if (dropdownCheckoutContainer.childElementCount <= 2) {
          notificationIconContainer.style.display = 'none';
        }
      });
    }

    console.log(cart);
  });

  i.addEventListener('mouseup', () => {
    document.getElementById('empty-cart').style.display = 'none';
    checkoutLink.removeAttribute('class', 'checkout-link-disabled');
  });
});
5
  • Could you share a bit more of your code (especially this click event handler)? Not sure why would you perform any action on a button that was not the "clicked" one. Commented Mar 16, 2020 at 11:56
  • Can you share the complete code for click handler including forEach loop as well? Commented Mar 16, 2020 at 11:56
  • Edited to include full code @Kox Commented Mar 16, 2020 at 11:58
  • Thanks @Daniel_Knights. Starting from the line if (cartItem.id !== currentCardId) {..., what is actually cartItem here? Is it bound to its addCartBtn? Commented Mar 16, 2020 at 12:04
  • @Kox cartItem is the inner-object initialised before the forEach() Commented Mar 16, 2020 at 12:08

1 Answer 1

1

suppose, You have a data like that

let cart = { 'cart-items': [{id: 1, name: 'test 1', price: 30.9, quantity: 1}] }

When You are going to click on button then currentCardId = 1

Then you need to the following at click event.

const existsIndex = cart['cart-items'].findIndex((item) => item.id === currentCardId )

if (existsIndex !== -1) { 
   cart['cart-items'][existsIndex].quantity++    
} else {
  cart['cart-items'].push({id: currentCardId, name: 'sadsad', quantity: 1}) 
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.