Updating various elements of an object within an array using a patch operation

Currently delving into the world of web development. Here I am, working on my first express server and facing a little challenge:

I am trying to update multiple values of an object within an array using app.patch, but struggling with the syntax.

While my current code gets the job done, I believe there might be a more elegant solution out there. Here's what I have so far:

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");
});

If anyone knows how to condense the five lines where foundTabak.x = x into one line, I would appreciate your input!

Thank you for your assistance!

Answer №1

If you're looking to update specific properties in an object, take a look at Object.assign.

It's important to ensure that req.body only includes the properties you intend to modify.

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");
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to customize the background of radio buttons in HTML

I want the background color to stay consistent as lightgray for each <ul>. Currently, clicking the radio button causes the ul's background to change incorrectly. I am unsure of how to loop through all available ul elements using jQuery and woul ...

Using Javascript/HTML to enable file uploads in Rails

I'm currently facing an issue with uploading and parsing a file in Rails, as well as displaying the file content in a sortable table. I followed a tutorial on to get started. This is what my index.html.erb View file looks like: <%= form_tag impo ...

Exploring the Power of Highcharts and MySQL

Currently, I am seeking assistance with a code that involves extracting data from a MySQL database and converting it into the required format for Highcharts. <?php $query =mysql_query("select date_format(connect_time,'%Y-%m-%d %H %i ...

A guide on retrieving information from a deeply nested object using pug

Is there a way to access data from a nested JSON object without the use of JavaScript in PUG? I need to loop through product highlights and extract the heading property. JSON FORMAT [{"id":"0.33454785604755677","title":"Product 2 Title", "hig ...

A guide on setting up a countdown timer in Angular 4 for a daily recurring event with the help of Rxjs Observable and the Async Pipe

I'm currently working on developing a countdown timer for a daily recurring event using Angular 4, RxJS Observables, and the Async Pipe feature. Let's take a look at my component implementation: interface Time { hours: number; minutes: numbe ...

Tips on submitting a single form and efficiently utilizing two submit buttons with validation in just one click

<form> <input type="submit" name="submit" id="formSubmit" value="SAVE FOR NOW" /> &nbsp;&nbsp;&nbsp; <input type="submit" name="submitAndConfirm" id="submitAndConfirm" value="CONFIRM AND UPLOAD TO SERVER" /> </f ...

Querying Mongoose to search for a particular value within an array of elements

My schema looks like this: var EntitySchema = new Schema({ name : {type: String, default: null}, organizations : [{ id: { type: mongoose.Schema.Types.ObjectId, ref: 'Organization' }}] }); I have the id of an organization ...

Is it possible for me to automatically add a line break following every image that is fetched from the Flickr API?

Hello there! I'm facing a little challenge with inserting a line break after each image that loads from the Flickr API. It's tricky to manipulate the style of data that hasn't loaded in the browser yet. I've experimented with using the ...

Acquiring and showcasing the mongoose schema property

Within my mongodb collection, I have a plethora of jokes stored, the schema is structured as below: const mongoose = require ("mongoose"); // Dad Joke Schema const jokeSchema = new mongoose.Schema({ content: String }); module.exports = mongoose.mode ...

What could be causing the 304 error when using $http.get?

I'm a newcomer to angular and facing an issue with a service that was functioning perfectly, but suddenly stopped. The service I am referring to has the following method. this.retrieveForms = function() { return $http.fetch("/forms"). then(fu ...

I am attempting to create a password validation system without the need for a database, using only a single

Help Needed: Trying to Create a Password Validation Website <script language="Javascript"> function checkPassword(x){ if (x == "HI"){ alert("Just Press Ok to Continue..."); } else { alert("Nope... not gonna happen"); } } ...

Display a collection of objects using Jade / Pug syntax

Struggling to find resources on Pug / Jade templating, turning to this platform for help. I've been diving into documentation on iterations along with consulting this helpful link. Working with Node.js, Express, and pug for a school project - a mock ...

Is there a specific index range in javascript or nodejs for accessing array items?

I recently came across this Ruby code snippet: module Plutus TAX_RATES = { (0..18_200) => { base_tax_amount: 0, tax_rate: 0 }, (18_201..37_000) => { base_tax_amount: 0, tax_rate: 0.19 }, (37_001..80_0 ...

Utilizing Express-sessions to generate a fresh session with each new request

I'm facing an issue with my express backend using express-sessions and Angular frontend. Every time the frontend makes a request, a new session is created by express-sessions. I suspect the problem lies in Angular not sending the cookie back, as I don ...

Deciphering JSON data within AngularJS

When I retrieve JSON data in my controller using $http.get, it looks like this: $http.get('http://webapp-app4car.rhcloud.com/product/feed.json').success(function(data) The retrieved data is in JSON format and I need to access the value correspo ...

Adjusting the size of a button in HTML and CSS

Check out this code: /* custom button */ *, *:after, *:before { box-sizing: border-box; } .checkbox { position: relative; display: inline-block; } .checkbox:after, .checkbox:before { font-family: FontAwesome; font-feature-settings: normal; - ...

Sending pictures from React to Express

When I try to upload images from the react state to express, I encounter an issue. Although texts are successfully sent and received in the backend, the images are not being transferred. The data remains as an empty array in my express route. This is the ...

Errors in Chartist.js Data Types

I am currently using the Chartist library to monitor various metrics for a website, but I have encountered some challenges with the plotting process. The main errors that are appearing include: TypeError: a.series.map is not a function TypeError: d.normal ...

Is it feasible to utilize Socket.io and Express in conjunction with templates without the need for routes?

Apologies for what might be considered a beginner question, but I'm curious if it's possible to run a Socket.io event server in one folder and have an HTML page utilize that server from a different folder. The reason for this question is because ...

Having trouble converting the file to binary format in order to send it to the wit.ai api through node.js

I am having trouble converting an Audio file to Binary format for sending it to the Wit.AI API. The node.js platform is being used for this purpose. On the front-end, user voice is recorded using the Mic-recorder Module. Any guidance or suggestions would b ...