简体   繁体   English

增加对象数量而不是在数组中创建新对象

[英]Increase object quantity instead of creating a new object in array

First time working with a shopping cart component, I have my code structured like this..第一次使用购物车组件时,我的代码结构如下..

let cartCount = document.getElementById("counter");
let isItemSelected = false;
let itemCount = 0;
let shoppingCart = [];
let selectedSize = "";
let displaySelectedSize = document.getElementById("selected");
let displayCart = document.getElementById("cart");



selectItem = () => {  
  isItemSelected = true;
  selectedSize = event.srcElement.id;
  displaySelectedSize.innerHTML = `${selectedSize}`;
}

addItem = () => {
  if (isItemSelected === true) {

    const shopItem = {
      name: "Classic Tee",
      price: 75,
      size: `${selectedSize}`,
      quantity: 0
    }

    itemCount+= 1;
    cartCount.innerHTML = `( ${itemCount} )`;    
    shopItem.quantity++
    shoppingCart.push(shopItem);
    console.log(shoppingCart);

    return itemSuccess();
  } else {
      return itemError();
  }
}

What I basically need is for the shopItem.quantity to increase if I have multiple of the selected size.如果我有多个所选尺寸,我基本上需要的是增加 shopItem.quantity 。

At the moment I get this..目前我得到这个..

// Output
0: {name: "Classic Tee", price: 75, size: "small", quantity: 1}
1: {name: "Classic Tee", price: 75, size: "small", quantity: 1}

// Desired Output
0: {name: "Classic Tee", price: 75, size: "small", quantity: 2}

I can see why my output is like that, it's creating a new object each time my addItem function is fired, but I would like to mutate my shopItem.quantity if there are duplicates...我可以明白为什么我的输出是这样的,每次我的 addItem 函数被触发时它都会创建一个新对象,但如果有重复,我想改变我的 shopItem.quantity ......

How would I do that?我该怎么做?

You can give item time an identity attribute (I would not go by name, since it is possible you can have something with the same name and that would be bad) such as id and the you can search for it before adding something.你可以给项目时间一个身份属性(我不会按名称去,因为你可能有同名的东西,这会很糟糕),比如id ,你可以在添加东西之前搜索它。 For example, consider the following item:例如,考虑以下项目:

const cartItem = {id: 1, name: "Classic Tee"}

Then before adding the item, you could look for it in the cart:然后在添加商品之前,您可以在购物车中查找它:

const existingItem = shoppingCart.find((item) => {
  return cartItem.id === item.id;
});

if(existingItem) {
   existingItem.quantity++;
} else {
  // Push the item into the cart
  shoppingCart.push(cartItem);
}

I think you should filter your shoppingCart array and depending on it if you should add a new item to the array or increment the quantity of an existing item.我认为您应该过滤您的 shoppingCart 数组,并根据它是否应该向数组添加新项目或增加现有项目的数量。

Here's a sample based on what you started.这是一个基于您开始的示例。 I removed some code so I can focus on the gist of what I mean我删除了一些代码,以便我可以专注于我的意思的要点

let shoppingCart = [];


addItem = (newItem) => {

    function itemFilter(item) {
        return item.name === newItem.name && item.price === newItem.price && item.size === newItem.size
    }
    let existingItems = shoppingCart.filter(itemFilter)

    if (existingItems.length > 0) {
        existingItems[0].quantity += newItem.quantity
    } else {
        shoppingCart.push(newItem)
    }

}

const shopItem = {
    name: "Classic Tee",
    price: 75,
    size: "small",
    quantity: 1
}

const shopItem2 = {
    name: "Classic Tee",
    price: 75,
    size: "big",
    quantity: 1
}

const shopItem3 = {
    name: "Classic Tee",
    price: 75,
    size: "small",
    quantity: 2
}

console.log('-----------')
console.log(shoppingCart)
addItem(shopItem)
console.log('-----------')
console.log(shoppingCart)
addItem(shopItem)
console.log('-----------')
console.log(shoppingCart)
addItem(shopItem2)
console.log('-----------')
console.log(shoppingCart)
addItem(shopItem)
console.log('-----------')
console.log(shoppingCart)

output is:输出是:

-----------
[]
-----------
[ { name: 'Classic Tee', price: 75, size: 'small', quantity: 1 } ]
-----------
[ { name: 'Classic Tee', price: 75, size: 'small', quantity: 2 } ]
-----------
[ { name: 'Classic Tee', price: 75, size: 'small', quantity: 2 },
  { name: 'Classic Tee', price: 75, size: 'big', quantity: 1 } ]
-----------
[ { name: 'Classic Tee', price: 75, size: 'small', quantity: 4 },
  { name: 'Classic Tee', price: 75, size: 'big', quantity: 1 } ]

You can also use reduce like this:你也可以像这样使用reduce

 const fakeGiftCardList2 = [ { value: 8, quantity: 1, cost: 3 }, { value: 8, quantity: 1, cost: 3 }, { value: 8, quantity: 1, cost: 3 }, { value: 8, quantity: 1, cost: 3 }, { value: 8, quantity: 1, cost: 3 }, { value: 10, quantity: 1, cost: 12 }, ]; const red = (obj, item) => { obj[item.value] ? (obj[item.value].quantity += 1) : (obj[item.value] = { ...item }); return obj; }; const arrayHashmap = fakeGiftCardList2.reduce(red, {}); const mergedArray = Object.values(arrayHashmap); console.log(mergedArray);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM