0

I`m new in React, I have array with server data (simplified)

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}
]

And another one from localStorage

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

I need to compare if obj in array one equal to obj in array two, change value bookmarked in first array to true and return a copy of the array. I don’t have any id, so I compare using label. Here is my code it works, but it doesn`t return copy, it mutates an original one.

 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])

1 Answers1

0

You can spread the recipes into a new array and use object destructuring to pull-out the recipe and bookmarked values for each item. You can then figure out the bookmarked state for each item in localRecipes.

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; }
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132