首页 > 解决方案 > 脚本 | 从数组中删除对象

问题描述

大家好我有点卡在我的项目中,现在我成功创建了一个可以添加项目的购物车,但现在我卡住了,因为我不知道如何创建一个删除特定项目而不是所有项目的函数从购物车。

var products = [
  {
   name:"Gta",
   price:15,
   catagory:"Games",
   inCart:0
  },
  {
    name:"Call of Duty",
    price:15,
    catagory:"Games",
    inCart:0
  },
  {
    name:"Sims",
    price:15,
    catagory:"Games",
    inCart:0
   },
   {
    name:"Razor",
    price:15,
    catagory:"Games",
    inCart:0
   },
   {
    name:"Age of Empire",
    price:15,
    catagory:"Games",
    inCart:0
   },
   {
    name:"Drive license",
    price:15,
    catagory:"Games",
    inCart:0
   },
   {
    name:"Halo",
    price:15,
    catagory:"Games",
    inCart:0
   }
];
function SetItem(product){

  let CartItems = localStorage.getItem("prodcutsInCart");
  CartItems = JSON.parse(CartItems);

  if(CartItems != null){
    if(CartItems[product.name] == undefined){
        CartItems = {
          ...CartItems,
          [product.name]:product
        }
     }
     CartItems[product.name].inCart +=1;
    }else{
      product.inCart = 1;
       CartItems = {
       [product.name]: product
        }

    }
    localStorage.setItem("prodcutsInCart",JSON.stringify(CartItems));
}

此外,我在“ProductsInCart”键下的本地存储中添加输出

{"undefined":{"name":"Call of Duty","price":15,"catagory":"Games","id":"id","inCart":3},"Call of Duty":{"name":"Call of Duty","price":15,"catagory":"Games","inCart":1}}

所以基本上我只是想弄清楚我如何删除特定的使命召唤游戏,而不是“ProductsInCart”键下的所有对象。

标签: javascript

解决方案


通过 array.filter 方法一次,然后再次将返回的数组设置为本地存储。


推荐阅读