【问题标题】:Iterate a property of Object in Array that Matches Query在匹配查询的数组中迭代对象的属性
【发布时间】:2021-12-22 01:03:38
【问题描述】:

我正在使用 React 并希望根据它是否与按下“迭代”按钮的项目匹配来迭代我的“购物车”数组中的对象的“数量”属性。

我原来的解决方案是这样的......

setCart((cart) => {
  const itemMatch = cart.find((cartItem) => cartItem.name === item.name);
  if (itemMatch !== undefined) {
    itemMatch.amount = itemMatch.amount + 1;
  } else {
    cart.push(item);
  }

  return [...cart];
})

但是,迭代是按二计数的。

我的第二个解决方案是这样...

setCart((cart) => {
  const updatedCart = cart.map((cartItem) => {
    if (cartItem.name === item.name) {
      return {...cartItem, amount: cartItem.amount + item.amount}
    } else {
      return cartItem
    }
  })

  return updatedCart;
})

此解决方案有效,但我无法弄清楚这两者之间的区别是什么。如果有人可以帮助解释真正有助于我理解的区别。谢谢。

【问题讨论】:

  • 你能详细说明一下用二来数吗?

标签: javascript reactjs iteration


【解决方案1】:

在第一个解决方案中,您将项目推送到已经拥有所有这些项目的现有数组中。

offtop:第二种解决方案在不改变现有数据方面也更好。

【讨论】:

    【解决方案2】:

    在这里,你正在做不同的事情。

    假设您有这样的示例输入:

    const item = { name: "abc", amount: 5 }
    const cart = [
        { name: "ab", amount: 15 },
        { name: "def", amount: 10 }
    ]
    

    在场景 1 中:

    const setCart = ((cart) => {
        /* first finding if the object which are already exist in cart array
         is also exist in item object or not. */
        const itemMatch = cart.find((cartItem) => cartItem.name === item.name);
        // if item found increase amount by 1
        if (itemMatch !== undefined) {
            itemMatch.amount = itemMatch.amount + 1;
        } else { // if item not found add that item to array
            
            cart.push(item);
        }
        // and returning it
        return [...cart];
    })
    
    // output
    /* [
        { name: 'ab', amount: 15 },
        { name: 'def', amount: 10 },
        { name: 'abc', amount: 5 }
    ] */
    

    在场景 2 中:

    const setCart = ((cart) => {
        //  looping into the cart array and searching if item exist in cart or not
        const updatedCart = cart.map((cartItem) => {
            // if item which are in cart is also exist
            if (cartItem.name === item.name) {
                // return all oder cart item, and update the amount 
                return {...cartItem, amount: cartItem.amount + item.amount }
            } else {
                // return the cart item as it is
                return cartItem
            }
        })
    
        // returning the cart array
        return updatedCart;
    })
    
    // output
    /* [
        { name: 'ab', amount: 15 },
        { name: 'def', amount: 10 }
    ] */
    

    在场景 2

    您永远无法将新商品添加到购物车中,因为您正在循环进入购物车商品并检查商品是否存在(如果存在则更新购物车,如果不存在则原样返回购物车商品)。

    在场景 1

    您首先要查找购物车中的商品是否存在,并确保该商品是否已存在于购物车中,只需更新金额,如果不存在,则将商品添加到购物车中。 (这在真实场景中有效)

    【讨论】:

      猜你喜欢
      • 2020-06-20
      • 1970-01-01
      • 2021-01-18
      • 1970-01-01
      • 2015-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多