我有两个数组inventory
和cartItems
。这两个数组中都有对象。
inventory
数组包含所有产品的列表。
cartItems
数组是用户将产品添加到购物车的数组。
我想比较数组,然后显示库存中剩余的项目。
下面是代码:
var inventory =
[
{ item: "apples", price: 19.95, qty: 50 },
{ item: "oranges", price: 20.99, qty: 40 },
{ item: "pineapples", price: 40.00, qty: 60 },
{ item: "lemons", price: 10.12, qty: 100 }
]
function MyBasket() {
this.totalItems = []
}
MyBasket.prototype.addItems = function(item, price, qty) {
this.totalItems.push({
"item": item,
"price": price,
"qty": qty
});
}
MyBasket.prototype.cartItems = function() {
return this.totalItems;
}
var cart = new MyBasket();
cart.addItems("banana", 10, 2);
cart.addItems("mango", 10, 3);
cart.addItems("x", 5, 4);
console.log('cart items', cart.cartItems())
答案 0 :(得分:1)
您可以遍历cartItems
并使用inventory
和find
来更新forEach
var inventory = [{item:"apples",price:19.95,qty:50},{item:"oranges",price:20.99,qty:40},{item:"pineapples",price:40.00,qty:60},{item:"lemons",price:10.12,qty:100}];
const cart = {
totalItems: [{
item: "apples",
price: 20,
qty: 2
}, {
item: "oranges",
price: 21,
qty: 3
}]
}
function updateInventory() {
cart.totalItems.forEach(i => {
const item = inventory.find(o => o.item === i.item);
if(item)
item.qty -= i.qty;
})
}
updateInventory()
console.log(inventory)