0

I am working on the React app, and there I have an array shopsAsArray. This array looks like this:

[
    {
       "shopName":"Billa",
       "ID":"01",
       "ratings":[
          {
             "stars":5,
             "comment":"Good assortiment."
          },
          {
             "stars":5,
             "comment":"Very Tasty Food!"
          }
       ]
    },
    {
       "shopName":"Albert",
       "ID":"02",
       "ratings":[
          {
             "stars":5,
             "comment":"Nice"
          },
          {
             "stars":4,
             "comment":"Not bad"
          }
       ]
    }
]

I need to add a new comment to one of these shops. This shop is the same as variable chosenShop. So my task is to add a new comment to the shop that has the same ID as chosenShop. I know that the next function is wrong, but I don’t know how to fix it:

shopsAsArray.get(chosenShop.ID).push(newComment);
Ajeet Shah
  • 18,551
  • 8
  • 57
  • 87
Helen
  • 157
  • 1
  • 8
  • 1
    `shopsAsArray.find(shop => shop.id === chosenShop.ID).ratings.push(newComment);` – VLAZ Mar 15 '21 at 09:33
  • Maybe shopsAsArray.find(shop => shop.id === chosenShop.ID).ratings.comment.push(newComment) would be better, but it still doesn't work... – Helen Mar 15 '21 at 10:22
  • 1
    OK, it was supposed to be `shop.ID` (capitals) my bad there but [it seems to work](https://jsbin.com/pipoqig/edit?js,console). If it doesn't, then there is not enough information in the question to know what's wrong. I assumed that `chosenShop.ID` is valid. – VLAZ Mar 15 '21 at 10:36
  • Can you advise me, please, what should I do, in the case when I have the next hook: const [shopsAsArray, setShopsAsArray] = useState(Object.keys (shopsInfo).map((pid) => shopsInfo[pid])); If I try this: let newRating={stars: newReview, comment: newComment}; setShopsAsArray (shopsAsArray.find(shop => shop.ID === chosenShop.ID).ratings.push(newRating)); It doesn’t work – Helen Mar 15 '21 at 12:49
  • 1
    If you are using react (your original question wasn't tagged with "react") and `shopsAsArray` is in react state, don't use `push` i.e. don't modify (mutate) the original state data. Instead, create a new copy and store that in state. – Ajeet Shah Mar 15 '21 at 13:00

0 Answers0