我有以下代码。现在,当调用构造函数时,就会创建对象。现在,当更新字段时,它们会像这样更新。请注意,我无法修改 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();
});
最佳答案
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()
});
关于javascript - JavaScript 中的对象声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33183212/