[英]Can't override property of an JavaScript object
I got a method that is formatting the date
property of a message
. 我有一个格式化
message
的date
属性的方法。 A user has an array of messages
. 用户具有一系列
messages
。
user.messages[i].date = formatDate(user.messages[i].date);
// logs the correctly formatted date
console.log(formatDate(user.messages[i].date));
// logs the unformatted date
console.log(user.messages[i].date);
However, when I do it like the following code snippet it works. 但是,当我按照以下代码片段进行操作时,它可以工作。
user.messages[i] = {
name: user.messages[i].name,
body: user.messages[i].body,
_id: user.messages[i]._id,
date: formatDate(user.messages[i].date)
};
With the help of the comment from @plalx, I found a solution in this thread: 借助@plalx的注释,我在此线程中找到了一个解决方案:
Stubbing virtual attributes of Mongoose model 对猫鼬模型的虚拟属性进行存根
This is a guess but you could add formatteddate:"" into your user model (or similar) and then try: 这是一个猜测,但您可以在用户模型(或类似模型)中添加formatteddate:“”,然后尝试:
user.messages[i].formatteddate = formatDate(user.messages[i].date);
Therefore you are not re-configuring it. 因此,您无需重新配置它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.