2016-09-21 3 views
0

だから私は、常に次の形式を持つオブジェクトを取得します。配列の中で、forriptをチェックする方法は?

student: { 
    "student_id": "12345", 

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

はありがとうと答えを受け入れ、upvoteう!トリックを行う必要があり、このような

答えて

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'オブジェクトを1つ追加するだけで正常に追加できましたが、' student_id'という2つの 'student'オブジェクトを追加しようとすると、最初の' classInfo'オブジェクトが正しく追加されました2番目の 'classInfo'オブジェクトが正しい場所に追加されましたが、' student_id'も追加されました。問題の原因はどこですか?私はログテストを試みましたが、それを見つけることができませんでした。おかげさまで再びjabclab –

+0

前のコメントは無視してください。私の終わりに間違いだった。どうもありがとうございます!答えを受け入れ、upvoted。しかし、学習目的のために、 'students.find(function(s))'は何をしていますか? –

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

あなたはstudent_idまたはプレーンアレーresultArrayでインデックス付けするオブジェクトが含まれてもresult形式を使用することができます。

+0

以前の回答が機能しました。関係なくあなたのupvoted;) –

+0

ありがとう。はい、以前の答えが動作しますが、find()のようなメソッドを使用しないため、コードが高速になります。これは、大規模な配列にとって特に重要です。 – IStranger

関連する問題