Revise an existing object by incorporating new information from a different object

One issue I am facing is related to a "Product" class that I use for creating and displaying products on my website. The constructor of this class looks like this:

constructor(title, price, description, imageUrl, id)
. To update an existing product with new information provided through a form on an "update product" page using a POST route in Express, I have the following code:

exports.postEditProduct = (req, res, next) => {
 const prodId = req.body.productId,
    updatedTitle = req.body.title,
    updatedPrice = req.body.price,
    updatedImageUrl = req.body.imageUrl,
    updatedDesc = req.body.description;

 const product = new Product(
    updatedTitle,
    updatedPrice,
    updatedDesc,
    updatedImageUrl,
    ObjectID(prodId) // Using mongodb!
); //additional promise-related code follows...

Thinking ahead, if I had to update a thousand properties manually, it would be a tedious task. This is where I'm looking for a solution - passing the updated props to the const product constructor without individually naming each one. Although defining variables in this manner is not ideal and is just for experimentation purposes, it's something I don't plan on implementing in production.

Answer №1

My proposal involves implementing the Factory Pattern, which serves to initialize the class instance. In JavaScript, we have the flexibility to opt for functions that generate an instance of a Product based on various parameters.

const keys = ['title', 'price', ...]

function createProduct(params) {
  const product = new Product()
  for (let x in params) {
    if(params.hasOwnProperty(x) && keys.includes(x)) {
      product['any prefix' + x] = params[x]
    }
  }
  return product
}


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

What are the steps to create fixed Angular Material Chips?

I'm currently attempting to achieve a similar look and functionality as demonstrated here: https://material.angularjs.org/1.1.9/demo/chips#static-chips where the chips are static and not selectable, clickable, or hoverable. However, I am utilizing Ang ...

Error in JSON parsing: Unexpected token 'u' at the beginning of the input in Angular2

I attempted to create a server using dummy data. Below is the System.js Config I have implemented (given that my routing is slightly different, this setup has been working well so far) System.config({ // baseURL to node_modules b ...

Interactive drop-down menu, utilizing $_GET method to handle spaces in input

I have successfully implemented a dynamic drop-down menu using JavaScript/jQuery and populated it with PHP MySQL: $("#first-choice").change(function() { $("#second-choice").load("getter.php?choice=" + $(this).val()); }); Everything is working as ...

Exploring ExpressJS: Integrating Domain Error Handling in Middleware

Expectations were set for the middleware bound to a specific Domain to be handled by the error handler designated for that domain. However, in my experience with Express, this turned out to not be the case. To address this discrepancy, I decided to creat ...

Designing a self-contained web component structure using an Immediately Invoked Function Expression (IIFE

I have developed a custom web component to display gists in any HTML content. Starting with the Lit Element Typescript Starter Project as a base, I customized the rollup.config.js file. The output format was changed to iife for easier script tag accessib ...

Discover the power of React Meteor, where reactive props and inner state work together

I am working with a component that utilizes the draft-js library for text editing. import React, { Component } from 'react' import { EditorState, convertToRaw } from 'draft-js' import { Editor } from 'react-draft-wysiwyg' imp ...

In Angular 5, a variable's value becomes undefined once it is subscribed to outside of its assigned

I keep encountering an undefined value when trying to assign the subscribed value to a variable in my code snippet below. service.ts getIpAddress() : Observable<any> { return this.http .get(this.Geo_Api) .map((response: ...

Trigger Vue to scroll an element into view once it becomes visible

I created a dynamic form that calculates 2 values and displays the result card only after all values are filled and submitted, utilizing the v-if directive. Vuetify is my chosen UI framework for this project. This is the approach I took: <template> ...

Direct users to a different page upon reloading the page in Django

Currently working on a web application with the Django framework. In one of the forms in my app, I am looking to automatically redirect to a new page upon reloading the current page, rather than when the form is submitted. Any insights from the community w ...

Troubleshooting challenges with setting up Nginx Reverse Proxy, ExpressJS, Angular, and SSL configurations

Being relatively new to this subject, I found myself with a few unanswered questions despite my efforts to search through Google. Here's what I understand so far - nginx functions as my webserver, responding to incoming requests by serving my client ...

"Exploring One Direction: A bright spotlight on navigating with PointerLockControls in Threejs

My goal is to attach a directional flashlight to the camera (controls object) so that the beam always points towards the center of the screen. Here's the code I'm currently using: controls = new PointerLockControls( camera, document.body ); var f ...

Combining Two Tables Using jQuery

I am currently attempting to combine two tables into one using jQuery in the following manner: var table = document.createElement("table"); table.id = "mergedTable"; $("#mergedTable > tbody:last") .append($("#csvInfoTable2 > tbody").html()) ...

Is it possible to center align a div without specifying the width?

After doing some research, it appears that the solution to my issue is not very promising. I want to avoid using a table for this particular case. My menu consists of 6 'a element' inline-blocks, which look great except for the fact that their wi ...

The issue arises when d3.scaleLinear returns NaN upon the second invocation

My journey with d3.js is just beginning and I'm taking it slow. Currently, I'm focused on creating a bar chart where data is loaded from a json file. When I click on the bars, the data changes to another column in the json. This is how my json f ...

Accessing querySelector for elements with numerical values in their name

Here is a URL snippet that I need to work with: <h1 id="header_2" title="mytitle" data-id="header_title" class="sampleclass " xpath="1">mytitle<span aria-label="sometest" class="sa ...

How is the same-domain policy applied to popup windows that have JavaScript enabled in the URL?

Is it possible to achieve something similar to this? var w = window.open("javascript: makeAnAjaxRequest();"); I'm curious whether the Ajax request, which is triggered after the new window is opened, would be considered a cross-site request. Does the ...

Modify the nearest symbol after the (touch) operation on Angular version 6

On my list, I have caret icons displayed on the left side which should change when clicked. Clicking on one icon should trigger a change in all other icons as well. <div class="caret" *ngIf="summary.isSupervisor" style="position: absolute; left: 15px ...

The challenge of handling multiple save conflicts in asynchronous Mongoose operations

My Node/Mongoose/Socket.io setup is presenting a challenging logic issue. Imagine a scenario where the Server model is frequently accessed and updated simultaneously in my application. db.Server.findOne({_id: reference.server}).exec(function(error, se ...

Leveraging the spread operator in cases where the value is null

Is there a more elegant solution for handling null values in the spread operator without using if-else statements? In this specific case, I only want to spread assignedStudents if it is not undefined. When attempting to do this without using if-else, I e ...

Anticipated that the absence of a value would match the presence of an Object

Struggling with running AngularJS unit tests for $resource using Jasmine v2.0 and Karma v0.13, I managed to convert custom actions to newer syntax successfully. However, a specific type of test is giving me trouble, which I suspect is related to $httpBacke ...