所以我将不断检索具有以下格式的对象:
student: {
"student_id": "12345",
"location": "below",
},
]
},
]
谢谢你,并接受回答和upvote!
答案 0 :(得分:2)
这样的事情可以解决问题:
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上提供了更多信息。
答案 1 :(得分:1)
使用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
格式。