Change multiple parts of object in Array with patch


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 => === id); = name
  foundTabak.brand = brand
  foundTabak.flavour = flavour
  foundTabak.score = score
  foundTabak.desc = desc

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

Thanks for your help!


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 => === id);
  Object.assign(foundTabak, req.body);

Answered By – Vid

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published