如何处理对象数组字符串并合并重复STUDENT_ID的属性值?
Merge Student Objects by STUDENT_ID
Got it, let's work through how to merge those student objects by their STUDENT_ID! Here's a straightforward approach using JavaScript, since your input is a JSON-formatted string:
Step-by-Step Solution
First, we'll parse the string into a JavaScript array, then use a map to group and merge entries by STUDENT_ID, combining MAJOR values into an array. We'll also add a check to handle any mismatched STATUS values (in case the same student has conflicting statuses).
Code Implementation
var str_obj = `[ { "STUDENT_ID": "ST001", "MAJOR": "SCIENCE", "STATUS": "1" }, { "STUDENT_ID": "ST002", "MAJOR": "SCIENCE", "STATUS": "1" }, { "STUDENT_ID": "ST002", "MAJOR": "HISTORY", "STATUS": "1" }, { "STUDENT_ID": "ST002", "MAJOR": "MATH", "STATUS": "1" }, { "STUDENT_ID": "ST003", "MAJOR": "HISTORY", "STATUS":"2" } ]`; // Parse the JSON string into a JS array const studentsArray = JSON.parse(str_obj); // Use an object to track merged students by their ID const mergedStudents = {}; // Iterate over each student entry studentsArray.forEach(student => { const { STUDENT_ID, MAJOR, STATUS } = student; if (!mergedStudents[STUDENT_ID]) { // If the ID doesn't exist yet, initialize a new entry mergedStudents[STUDENT_ID] = { STUDENT_ID, MAJOR: [MAJOR], STATUS }; } else { // Add the current major to the existing entry's major array mergedStudents[STUDENT_ID].MAJOR.push(MAJOR); // Optional: Warn if there's a status mismatch for the same student if (mergedStudents[STUDENT_ID].STATUS !== STATUS) { console.warn(`Warning: STUDENT_ID ${STUDENT_ID} has conflicting STATUS values: ${mergedStudents[STUDENT_ID].STATUS} vs ${STATUS}`); } } }); // Convert the merged object values back to an array const finalResult = Object.values(mergedStudents); // If you need the result as a string again, use JSON.stringify const finalResultStr = JSON.stringify(finalResult, null, 2); console.log(finalResultStr);
Output Result
Running this code will give you the merged array (as a formatted string):
[ { "STUDENT_ID": "ST001", "MAJOR": [ "SCIENCE" ], "STATUS": "1" }, { "STUDENT_ID": "ST002", "MAJOR": [ "SCIENCE", "HISTORY", "MATH" ], "STATUS": "1" }, { "STUDENT_ID": "ST003", "MAJOR": [ "HISTORY" ], "STATUS": "2" } ]
Notes
- If you expect
STATUSvalues might differ for the sameSTUDENT_ID, you can adjust the logic: for example, store all statuses in an array, or keep the latest one instead of showing a warning. - The
JSON.stringifystep is optional if you just need the JavaScript array for further processing.
内容的提问来源于stack exchange,提问作者ashura91
相关产品推荐
相关产品推荐

