2016-09-21 92 views

回答

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); 
} 

你可以这样调用它,如下所示:可用here

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

Runnable的JSBin例子。

更多信息请登陆Array.prototype.findat MDN

+0

刚刚给了它一个尝试,并与一个'学生'对象,它能够添加成功,但是当我试图添加两个'student'对象具有相同的'student_id',第一个'classInfo'对象被正确添加,第二个'classInfo'对象被添加到了正确的位置,但是里面还有'student_id'。哪里可能导致问题?我尝试过日志测试,但似乎无法找到它。再次感谢jabclab –

+0

不理会以前的评论。我的目标是错误的。非常感谢!接受了答案,并upvoted。但为了学习的目的,'student.find(函数)'是做什么的? –

+0

@JoKo很高兴帮助:-)你可以在这里阅读更多关于'Array.prototype.find'的信息https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find。 – jabclab

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索引。

+0

先前的答案奏效。不管upvoted你的;) –

+0

谢谢。是的,以前的答案有效,但是我的代码更快,因为它不使用find()等方法。这对于大型阵列尤为重要。 – IStranger