Home > Back-end >  Change multiple parts of object in Array with patch
Change multiple parts of object in Array with patch

Time:08-12

I'm currently learning the basics of web-dev. Sitting here on my first express-server and run into the following problem:

I want to update multiple values of an object inside an Array with app.patch and don't find the right syntax to do.

My current code is working, but I am sure there's a nice way of doing this. Here's the code:

app.patch("/tabak/:id", (req, res) => {
  const { id } = req.params;
  const { name, brand, flavour, score, desc } = req.body;
  const foundTabak = tabakArray.find(t => t.id === id);
  foundTabak.name = name
  foundTabak.brand = brand
  foundTabak.flavour = flavour
  foundTabak.score = score
  foundTabak.desc = desc
  res.redirect("/tabak");
});

So i want to make the five lines with foundTabak.x = x in one line.

Thanks for your help!

CodePudding user response:

Check out Object.assign.

Also make sure req.body only contains the properties you want to set.

app.patch("/tabak/:id", (req, res) => {
  const { id } = req.params;
  const foundTabak = tabakArray.find(t => t.id === id);
 
  Object.assign(foundTabak, req.body);
 
  res.redirect("/tabak");
});

  • Related