首页 > 解决方案 > 未添加到 JavaScript 对象的新元素

问题描述

该数组类似于:

var students = [
  {
    classes: [ 60757198250eab6930e73c01, 607572d41134b063103aba99 ],       
    _id: 604ede883a1fa43120dad097,
    name: 'Ravi Keshri',
    username: '2019ca44',
    password: '$2a$10$h0BAsOLKH92G1Vl1WNCSL.fvX22xyo1.Eeck792HtD0uCJPcvfv/q',
    email: 'ravikeshri.rk1@gmail.com',
    isTeacher: false,
    stream: 'btech',
    department: 'ee',
    phone: '9999999999',
    __v: 12
  }
]

我想为这些对象添加一个新属性“出席”。

User.find().where('_id').in(studentsIds).exec((err, students) => {
  if(err) {
      console.log(err);
      res.redirect('/teacher/dashboard');
  } else {

      students.forEach(function(student){
          var found = cls.students.find(function(val){return student._id.equals(val.id)});
          var attNum = found.attendance.length;
          var attDeno = cls.dates.length;
          var att = 0;

          if(attDeno != 0) att = (attNum / attDeno)*100;
          
          console.log(student);
          
          // =============================================
          // this is the part where I am facing this issue
          
          // student.attendance = att;
          // student["attendance"] = att;
          // none of the above working
          
          // =============================================
          
          console.log(student);
      });

      console.log(students);
      res.render("teacher/class", { students: students, cls: cls, teacher: teacher, user: req.user });
  }
 });

看了很多文章试过

obj.property = value;
obj["property"] = value;

即使我尝试 Array.map 添加一个新字段,但它不起作用。没有错误来。不知道我错过了什么。请帮帮我。

标签: javascripthtmlnode.jsmongodbmongoose

解决方案


推荐阅读