如何从localStorage的数组中取对象值与新值比较并校验重复?
实现方案
核心修改点
- 修正localStorage读取时的默认值格式错误,避免JSON解析抛出异常
- 调用数组
some()方法判断已存列表中是否有Title匹配的条目 - 匹配到重复条目直接给出提示终止执行,未匹配到再执行新增存储逻辑
完整修改后代码
const RecipeList = ({recipe}) => { const setData = () => { const newTitle = recipe.label; // 修正默认值:JSON.parse需要接收JSON字符串,取不到值时传入"[]" const existedFavRecipe = JSON.parse(localStorage.getItem('FavRecipes') || "[]"); // 判断是否存在重复Title的条目 const isDuplicated = existedFavRecipe.some(item => item.Title === newTitle); if (isDuplicated) { // 可替换为你项目使用的提示组件逻辑 alert('该食谱已经在收藏列表中'); return; } // 无重复则创建新对象存入本地存储 const NewFavRecipe = { Title : recipe.label, Image : recipe.image, Url : recipe.url, CuisineType : recipe.cuisineType, mealType : recipe.mealType, IngredientList: recipe.ingredients, // 注意确保作用域内已定义click变量,否则此处会报错 Status : JSON.stringify(click) } existedFavRecipe.push(NewFavRecipe); localStorage.setItem('FavRecipes',JSON.stringify(existedFavRecipe)); } }
逻辑说明
some()方法会遍历数组,只要有一个元素满足判断条件就立刻返回true,不需要遍历整个数组,性能优于filter()、find()等方法,非常适合仅需判断条目是否存在的场景。
内容的提问来源于stack exchange,提问作者Woppy
相关产品推荐
相关产品推荐

