繁体   English   中英

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

[英]console.log not showing expected object properties

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

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

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

您可能有一个Document对象而不是普通对象。 它们有一个自定义的toJSON方法 ,它只产生你的模式和_id的属性,但没有别的。 如果您使用for-in-loop将该方法复制到appointment对象上,则在记录时它将以不同方式进行序列化。

尝试

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

appointment.test= "res";

console.log(appointment);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM