You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

带选项数组的商品加入购物车,如何判断是否存在同款同选项商品?

购物车添加逻辑修改方案

原逻辑仅通过商品ID判断购物车中是否存在同款,存在则增加数量,不存在则新增。现需调整为:仅当购物车中存在相同ID且options选项完全一致的商品时,才增加该商品的数量;否则添加新的商品条目。


商品与选项接口定义(含中文注释)

// 商品接口
export interface Coffee {
  id: number;
  tags: string[]; // 标签集合
  name: string; // 商品名称
  description: string; // 商品描述
  photo: string; // 商品图片地址
  price: number; // 商品单价
  options: Options[]; // 可选配料(如牛奶、奶油、糖等)
}

// 选项接口
export interface Options { 
  id: number; // 选项唯一标识
  name: string; // 选项名称
  price: number; // 选项加价金额
}

原实现代码

function addCoffeeToCart(coffee: CartItem) {
    // 仅通过商品ID判断是否已存在
    const coffeeAlreadyExistsInCart = cartItems.findIndex(
      (cartItem) => cartItem.id === coffee.id 
    );

    const newCart = produce(cartItems, (draft) => {
      if (coffeeAlreadyExistsInCart < 0) {
        draft.push(coffee);
      } else {
        draft[coffeeAlreadyExistsInCart].quantity += coffee.quantity;
      }
    });

    setCartItems(newCart);
  }

修改后的实现代码

function addCoffeeToCart(coffee: CartItem) {
    // 同时校验商品ID和选项是否完全匹配
    const coffeeAlreadyExistsInCart = cartItems.findIndex((cartItem) => {
      // 第一步:校验商品ID是否一致
      if (cartItem.id !== coffee.id) return false;
      // 第二步:快速校验选项数量是否一致(数量不同直接排除)
      if (cartItem.options.length !== coffee.options.length) return false;
      // 第三步:逐一比对选项的唯一ID,确保所有选项完全匹配
      return cartItem.options.every(
        (itemOpt, index) => itemOpt.id === coffee.options[index].id
      );
    });

    const newCart = produce(cartItems, (draft) => {
      if (coffeeAlreadyExistsInCart < 0) {
        draft.push(coffee);
      } else {
        draft[coffeeAlreadyExistsInCart].quantity += coffee.quantity;
      }
    });

    setCartItems(newCart);
  }

关键改动说明

  1. 扩展匹配逻辑:不再仅依赖商品ID,而是同时校验选项的一致性
  2. 高效校验顺序:先比对ID,再比对选项数量,最后逐个比对选项ID,减少不必要的计算
  3. 可靠的选项匹配:使用选项ID而非名称进行比对,避免因名称重复、拼写差异导致的匹配错误

内容的提问来源于stack exchange,提问作者dtk77

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 06:40:21