console.log没有显示预期的对象属性 [英] console.log not showing expected object properties

查看:91
本文介绍了console.log没有显示预期的对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在node.js应用程序中的javascript中包含以下代码. 但是,某些对象未存储在我的变量appointment中.即使设置了它们,当我直接访问它们时,它也起作用:console.log(appointment.test);

I have the following code in javascript in my node.js application. However certain objects are not stored in my variable appointment. Even if I set them, when I directly access them it works: console.log(appointment.test);

我在这段代码中做错了什么?

What have I done wrong in this code?

var appointment = {
    subscribed: false,
    enoughAssis: false,
    studentSlotsOpen: false
};
console.log(appointment);
for (var key in appointmentsDB[i]) {
    appointment[key] = appointmentsDB[i][key];    
}

appointment.test= "res";

console.log(appointment.test);
console.log(appointment);

这是产生的输出:

{ subscribed: false,
  enoughAssis: false,
  studentSlotsOpen: false }
res
{ comment: 'fsadsf',
  room: 'dqfa',
  reqAssi: 3,
  maxStud: 20,
  timeSlot: 8,
  week: 31,
  year: 2013,
  day: 3,
  _id: 51f957e1200cb0803f000001,
  students: [],
  assis: [] }

变量console.log(appointmentsDB[i])看起来是:

{ comment: 'fsadsf',
  room: 'dqfa',
  reqAssi: 3,
  maxStud: 20,
  timeSlot: 8,
  week: 31,
  year: 2013,
  day: 3,
  _id: 51f957e1200cb0803f000001,
  students: [],
  assis: [] }

以下命令:

console.log(Object.getOwnPropertyNames(appointmentsDB[i]), Object.getOwnPropertyNames(Object.getPrototypeOf(appointmentsDB[i])));

显示:

[ '_activePaths',
  '_events',
  'errors',
  '_maxListeners',
  '_selected',
  '_saveError',
  '_posts',
  'save',
  '_pres',
  '_validationError',
  '_strictMode',
  'isNew',
  '_doc',
  '_shardval' ] [ 'assis',
  'timeSlot',
  'db',
  '_schema',
  'id',
  'base',
  'day',
  'collection',
  'reqAssi',
  'constructor',
  'comment',
  'year',
  'room',
  'students',
  'week',
  '_id',
  'maxStud' ]

但是,我希望我的最后一个输出还提供条目test,subscribed,足够的assis和studentSlotsOpen.这段代码有什么问题?

However I would expect that my last output also provides the entries test, subscribed, enoughAssis and studentSlotsOpen. What is wrong in this code?

我找到的解决方案是手动复制我想要的元素.

The solution I found was to manually copy the elements I wanted to.

推荐答案

您可能有一个文档对象,而不是普通对象.它们具有自定义的 toJSON方法,该方法仅产生架构的属性,并且_id,但仅此而已.如果将带有for-in-loop的方法复制到appointment对象,则登录时它也将以不同的方式进行序列化.

You probably have a Document object instead of a plain object. Those have a custom toJSON method which only yields the properties of your schema and the _id, but nothing else. If you are copying that method with your for-in-loop onto the appointment object, it will get serialized differently as well when logged.

尝试

for (var key in appointmentsDB[i].toObject()) {
    appointment[key] = appointmentsDB[i][key];    
}

appointment.test= "res";

console.log(appointment);

这篇关于console.log没有显示预期的对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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