首页 > 解决方案 > 使用源对象更新目标对象

问题描述

我的问题是我有一个“产品”类,我用它来创建产品并将它们呈现在我的页面中。这个对象有一个这样的构造函数:constructor(title, price, description, imageUrl, id),我有一个函数来更新一个现有的产品,通过“更新产品”页面中的一个表单从请求正文中获取它的新道具——然后是一个 POST 路由,就像这样(使用 express):

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) // I'm using mongodb!
); //rest of the code is just promise stuff...

现在,每当我手动做某事太多次时,我都会想“如果我有一千个这样的东西会怎样”?如果我的对象有一千个道具要更新怎么办?这就是我要解决的问题!使用我将更新的道具传递给构造函数的变量,const product而无需命名其中的每一个。另外,我知道定义这样的变量并不酷,我只是在这一点上搞砸了,这不会投入生产。

标签: javascriptexpressobjectecmascript-6

解决方案


我将介绍用于启动类实例的工厂模式。使用 JavaScript,我们可以自由地使用创建 Product 实例的函数,这些函数依赖于大量不同的参数。

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
}



推荐阅读