所以我會不斷地檢索與以下格式的對象:在數組中,如何檢查forript?
student: {
"student_id": "12345",
"location": "below",
},
]
},
]
謝謝你,將接受答案,並給予好評!
所以我會不斷地檢索與以下格式的對象:在數組中,如何檢查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);
}
你可以這樣調用它,如下所示:可用here
addStudent({
"student_id": "67890",
"class_number": "abcd",
"location": "below",
});
Runnable的JSBin例子。
更多信息請登陸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
索引。
先前的答案奏效。不管upvoted你的;) –
謝謝。是的,以前的答案有效,但是我的代碼更快,因爲它不使用find()等方法。這對於大型陣列尤爲重要。 – IStranger
剛剛給了它一個嘗試,並與一個'學生'對象,它能夠添加成功,但是當我試圖添加兩個'student'對象具有相同的'student_id',第一個'classInfo'對象被正確添加,第二個'classInfo'對象被添加到了正確的位置,但是裏面還有'student_id'。哪裏可能導致問題?我嘗試過日誌測試,但似乎無法找到它。再次感謝jabclab –
不理會以前的評論。我的目標是錯誤的。非常感謝!接受了答案,並upvoted。但爲了學習的目的,'student.find(函數)'是做什麼的? –
@JoKo很高興幫助:-)你可以在這裏閱讀更多關於'Array.prototype.find'的信息https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find。 – jabclab