在数组内部,如何检查是否有错误?

Inside an array, how to check forript?

所以我将不断检索具有以下格式的对象:

student: {
    "student_id": "12345",

                "location": "below",
            },
        ]
    },
]

谢谢,会接受回答和点赞!

像这样应该可以解决问题:

var students = [];

function addStudent(student) {
  // Check if we already know about this student.
  var existingRecord = students.find(function (s) {
    return s.student_id === student.student_id;
  });

  var classInfo = {
    class_number: student.class_number,
    location: student.location
  };

  if (!existingRecord) {
    // This is the first record for this student so we construct
    // the complete record and add it.
    students.push({
      student_id: student.student_id,
      classes: [classInfo]
    });

    return;
  }

  // Add to the existing student's classes.
  existingRecord.classes.push(classInfo);
}

然后您将按如下方式调用它:

addStudent({
    "student_id": "67890",
    "class_number": "abcd",
    "location": "below",
});

可运行的 JSBin 示例可用 here

Array.prototype.find at MDN.

上有更多内容

这个问题可以通过 student_id 使用索引来解决。例如:

var sourceArray = [{...}, {...}, ...];

var result = {};

sourceArray.forEach(function(student){

    var classInfo = {
        class_number: student.class_number,
        location    : student.location
    };

    if(result[student.student_id]){

        result[student.student_id].classes.push(classInfo);

    } else {

        result[student.student_id] = {
            student_id  : student.student_id,
            classes     : [classInfo]
        }

    }
});


// Strip keys: convert to plain array

var resultArray = [];

for (key in result) {
    resultArray.push(result[key]);
}

您还可以使用包含对象的 result 格式,由 student_id 或普通数组 resultArray 索引。