javascript - 脚本 | 从数组中删除对象
问题描述
大家好我有点卡在我的项目中,现在我成功创建了一个可以添加项目的购物车,但现在我卡住了,因为我不知道如何创建一个删除特定项目而不是所有项目的函数从购物车。
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”键下的所有对象。
解决方案
通过 array.filter 方法一次,然后再次将返回的数组设置为本地存储。
推荐阅读
- javascript - 选项卡单击在悬停时附加了上下文菜单时不起作用
- java - 如何找到以下代码的最坏情况复杂性?
- javascript - 在 Node.JS 中,我将如何使用 Google Sheets API 向上“移动”整个值范围?
- python - TensorFlow中是否有任何功能相当于python reduce?
- c# - 如何在 C# 中将空格/空值分配给二维数组
- azure - Azure Web App For Linux 的文件夹权限
- ssas - MDX 中的案例陈述
- php - 到达 PHP 对象子元素
- javascript - 我们可以处理 adf 托管 bean 中的引发应用程序错误吗
- python - 如何在 Pandas 中加载由键:值对组成的 CSV 文件