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

对比array与object去重后返回对象数组的addToCart功能实现问题

实现方案

核心逻辑说明

对象无法直接做全等对比,我们选择商品唯一标识id作为重复判断依据,逻辑如下:

  • 先过滤删除购物车cart中和传入对象id一致的已有重复项
  • 将新传入的对象追加到过滤后的数组中,保证最终仅保留一份目标对象
  • 同时返回处理后的购物车数组

完整可运行代码

首先修正原基础代码的语法问题(allProducts数组中每个对象末尾缺少逗号),再补全函数:

const allProducts=[
    { id:1, productName:'Apple',price:100,quantity:1},
    { id:2, productName:'Cherry',price:70,quantity:1},
    { id:3, productName:'Orange',price:60,quantity:1},
    { id:4, productName:'Grapes',price:69,quantity:1}
]

let cart =[]

const addToCart = (object) => {
    // 过滤掉所有和传入对象id重复的已有项
    const noRepeatCart = cart.filter(item => item.id !== object.id)
    // 加入新对象后更新cart,并返回结果
    cart = [...noRepeatCart, object]
    return cart
}

效果测试

调用方法传入目标对象:

const targetObj = { id:4, productName:'Grapes',price:69,quantity:1}
console.log(addToCart(targetObj))

输出结果和你预期的一致:

[
    { id:4, productName:'Grapes',price:69,quantity:1}
]

拓展说明(可选)

如果你需要的是「存在则删除,不存在则添加」的切换逻辑,可以改成如下实现:

const addToCart = (object) => {
    const isExist = cart.some(item => item.id === object.id)
    if (isExist) {
        cart = cart.filter(item => item.id !== object.id)
    } else {
        cart.push(object)
    }
    return cart
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 20:30:03