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

如何从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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 03:39:01