console.log未显示预期的对象属性

console.log not showing expected object properties

本文关键字:对象 属性 log 显示 console      更新时间:2023-09-26

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

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

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' ]

然而,我希望我的最后一个输出还提供了条目测试、订阅、enoughAssis和studentSlotsOpen。这个代码出了什么问题?

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

您可能有一个Document对象而不是普通对象。它们有一个自定义的toJSON方法,只生成模式和_id的属性,而不生成其他属性。如果您使用for in循环将该方法复制到appointment对象上,那么在记录时,它也会以不同的方式序列化。

尝试

for (var key in appointmentsDB[i].toObject()) {
    appointment[key] = appointmentsDB[i][key];    
}
appointment.test= "res";
console.log(appointment);