对象值替换现有对象值-Javascript

时间:2020-03-16 11:47:59

标签: javascript

我正在尝试创建一个内部包含多个对象的数组的对象,每个内部对象代表一张卡。

我在forEach()循环之外初始化所有三个对象,将每个项目推入数组,然后将该数组分配给外部对象中的键:

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

cart['cart-items'] = cartItems;

cartItems.push(cartItem); 

forEach()内部,每次单击该卡按钮时,都会获取卡数据,并将其分配给内部对象:

///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()

如果我多次单击同一按钮,这会增加“卡”的“数量”,但是当我单击单独的按钮时,它将覆盖现有卡,并且它是“数量”值。

我知道,如果我在循环内初始化cartItemcartItems可以防止这种覆盖,但是卡“ quantity”不会增加,它只会创建一个带有“ quantity”的单独对象'1'。

您知道我该如何解决吗?

修改

完整代码:

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');
  });
});

1 个答案:

答案 0 :(得分:1)

假设,您有这样的数据

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

当您要单击按钮时,那么currentCardId = 1

然后,在点击事件中需要执行以下操作。

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}) 
}