javascript - JavaScript 中的对象声明

标签 javascript node.js

我有以下代码。现在,当调用构造函数时,就会创建对象。现在,当更新字段时,它们会像这样更新。请注意,我无法修改 Comment(),因为它是由 mongoose 创建的。

  var newComment = new Comment();
  newComment.content = req.body.content;
  newComment.user.id = req.body.id;
  newComment.user.name = req.body.name;
  newComment.user.profilePicture = req.user.profilePicture;
  newComment.votes.up = [];
  newComment.votes.down = [];
  newComment.comments = [];
  newComment.timestamp = Date.now();

有没有办法像这样更新对象:

newComment.SOMEFUNCTION({
  content = req.body.content;
  user.id = req.body.id;
  user.name = req.body.name;
  user.profilePicture = req.user.profilePicture;
  votes.up = [];
  votes.down = [];
  comments = [];
  timestamp = Date.now();
});

最佳答案

Object.assign

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object.

Object.assign( newComment, {
    content : req.body.content,
    user : {
      id : req.body.id,
      name : req.body.name,
      profilePicture : req.user.profilePicture
    },
  votes.up : [],
  votes.down : [],
  comments : [],
  timestamp : Date.now()
});

http://jsfiddle.net/r8pavnuv/

关于javascript - JavaScript 中的对象声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33183212/

相关文章:

node.js - Fastify 是如何计算响应时间的?

MySQL 触发器通知客户端

javascript - 从razorpage调用另一个目录中的javascript函数

javascript - 按键事件后获取表单字段的值

javascript - node.js 模块应该导出命名函数还是对象?

javascript - 我是否正确地散列密码?

node.js - 计算机重新启动时重置 Node 版本

javascript - Knex.js 和 MySQL : Casting Integer into Boolean for bulk select

javascript - 变量似乎没有获得新值

javascript - 从 mathjax 纸质输入 polymer 对象中提取输入值