javascript - 对象值替换现有对象值 - 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()
如果我多次单击同一个按钮,这会增加“卡”的“数量”,但是当我单击一个单独的按钮时,它会覆盖现有的卡,它是“数量”值。
我知道如果我初始化cartItem
并cartItems
在循环内它可以防止这种覆盖,但是卡片的“数量”不会增加,它只会创建一个“数量”为“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');
});
});
解决方案
假设,你有这样的数据
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})
}
推荐阅读
- asterisk - 仅提取 Asterisk 上的注册联系信息
- netbeans - Netbeans Msys2 使 Cygwin1.dll 问题
- flutter - 选择项目时,颤振不更新放置在对话框中的 DropdownButton
- windows-10 - Windows 上的 Netbeans 12 不允许我连接 Tomcat
- pytorch - 如何将 AMD GPU 用于 fastai/pytorch?
- java - 建立三个表之间的关系
- asp.net-mvc - 来自本地服务器的 Power BI 报表集成
- javascript - Vuejs Nuxt - 如何修改 facebook 登录按钮样式?
- java - 无法执行shell脚本
- haskell - 你如何确定一个类型是否是一个函子在haskell中?