如何比较和深拷贝反应

How to compare and deep copy react

我是 React 新手,我有服务器数据数组(简化)

let recipes = [
  {"recipe": {label: "Chicken Vesuvio"},"bookmarked":false,"bought":false},
  {"recipe": {label: "Chicken Paprikash"},"bookmarked":false,"bought":false},
  {"recipe": {label: "Baked Chicken"},"bookmarked":false,"bought":false},
  {"recipe": {label: "Chicken Liver Pâté"},"bookmarked":false,"bought":false}
]

还有一个来自 localStorage

let localRecipes = [
  {"recipe": {label: "Chicken Vesuvio"},"bookmarked":true,"bought":false},
  {"recipe": {label: "Chicken Paprikash"},"bookmarked":true,"bought":false},
]  

我需要比较数组 1 中的 obj 是否等于数组 2 中的 obj,将第一个数组中的书签值更改为 true 和 return 数组的副本。我没有任何id,所以我使用label进行比较。这是我的代码,它可以工作,但它不会 return 复制,它会改变原始代码。

 useEffect(() => {
    if(recipes && recipes.length) {
        for (let i = 0; i < localRecipes.length; i++) {
            if(recipes[i].recipe.label == localRecipes[i].recipe.label) {
                recipes[i].bookmarked = true
            }
        }
    }
}, [isFetching])

您可以将 recipes 散布到一个新数组中,并使用对象解构来提取每个项目的 recipebookmarked 值。然后,您可以计算出 localRecipes.

中每个项目的 bookmarked 状态

const recipes = [
  { "recipe": { "label": "Chicken Vesuvio"    }, "bookmarked": false, "bought":false },
  { "recipe": { "label": "Chicken Paprikash"  }, "bookmarked": false, "bought":false },
  { "recipe": { "label": "Baked Chicken"      }, "bookmarked": false, "bought":false },
  { "recipe": { "label": "Chicken Liver Pâté" }, "bookmarked": false, "bought":false }
];

const localRecipes = [
  { "recipe": { "label": "Chicken Vesuvio"   }, "bookmarked": true, "bought": false },
  { "recipe": { "label": "Chicken Paprikash" }, "bookmarked": true, "bought": false },
];

const merged = [
  ...recipes.map(({ recipe, bookmarked, ...rest }) => ({
    ...rest,
    recipe,
    bookmarked: localRecipes
      .find(({ recipe: { label } }) => label === recipe.label)
        ?.bookmarked || bookmarked
  }))
]

console.log(merged);  // Merge remote with local storage
console.log(recipes); // Remote is uneffected
.as-console-wrapper { top: 0; max-height: 100% !important; }