Object.assign无法正常工作 [英] Object.assign not working as expected

查看:126
本文介绍了Object.assign无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象叫预订,里面有几个属性,我想用Object.assign扩展,像这样:

  let data = Object.assign(booking,{
hiw:event.hiw [booking.locale],
tips:event.tip [booking.locale],
start: moment(event.start).format('L')
});

但是当我打印数据时,结果将是源(预订)中相同的对象,所以 hiw 提示开始将被忽略,但...如果我尝试做:

  let data = Object.assign({},{
hiw: event.hiw [booking.locale],
tips:event.tip [booking.locale],
start:moment(event.start).format('L')
});

这将很完美。



我的问题是:我在这里做错什么?为什么我不能扩展预订,我可以扩展空对象?



这绝对不是异步的问题代码,当我尝试延长预订时,他已经存在所有的物业内。



我也试图使用下划线 extend 方法,行为是完全相同的。

解决方案

Mongoose文件(模型实例)是特殊的: print / )它们(如果您将文档转换为具有 obj.toObject()的简单JS对象,则不会。)



这意味着使用 Object.assign()将只有在分配模式中也存在的属性时才有效。任何未声明的属性都不会显示(也不会保存到数据库中)。



如果您打算使用该文档输出,则应将其转换为一个适当的JS对象首先分配给它:

  let data = Object.assign(booking.toObject(),{
hiw:event.hiw [booking.locale],
tips:event.tip [booking.locale],
开始:moment(event.start).format('L')
});


I have one object called bookings, and inside it I have several properties, and i want extend with Object.assign, like this:

let data = Object.assign(booking, {
  hiw: event.hiw[booking.locale],
  tip: event.tip[booking.locale],
  start: moment(event.start).format('L')
});

But when I print the data, the result will be the same object from the source (booking), so hiw, tip and start will be ignored, but... if I try to do:

let data = Object.assign({}, {
  hiw: event.hiw[booking.locale],
  tip: event.tip[booking.locale],
  start: moment(event.start).format('L')
});

This will work perfect.

My question is: what am I doing wrong here? Why can't I extend booking and I can extend the empty object?

That's definitely not a problem with async code, when i try to extend booking, he already exist with all properties inside.

I also was trying to use underscore extend method, and the behavior is exactly the same.

解决方案

Mongoose documents (model instances) are special: they will only print properties that are present in the schema.

If properties aren't defined there, they won't show up when you console.log() them (and also not if you convert the document to a plain JS object with obj.toObject()).

This means that using Object.assign() will only work if you assign properties that are also present in the schema. Any properties that aren't declared will not be shown (nor saved to the database).

If your intention is to use the document for output, you should convert it to a proper JS object first before assigning to it:

let data = Object.assign(booking.toObject(), {
  hiw   : event.hiw[booking.locale],
  tip   : event.tip[booking.locale],
  start : moment(event.start).format('L')
});

这篇关于Object.assign无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆