2017-05-24 11 views
0

のグループから複数のオブジェクトを削除し、私は「合格」を持つ配列「ドキュメント>試験」内の全オブジェクトをスプライスしたいと思います:「NO」 私はこのアレイ

var docs = [ 
 
       {"Id":1,"Name":"First","Exam":[{"Pass":"No"},{"Sub":"T1"}]}, 
 
       {"Id":2,"Name":"Second","Exam":[{"Pass":"Yes"},{"Sub":"T2"}]}, 
 
       {"Id":3,"Name":"Third","Exam":[{"Pass":"No"},{"Sub":"T3"}]} 
 
       ]; 
 

 
for (var i = docs.length - 1; i >= 0; i--) { 
 
    for (var j = docs[i].Exam.length - 1; j >= 0; j--) { 
 
      if (docs[i].Exam[j].Pass == 'No') { 
 
       docs.splice(docs[i],1); 
 
      } 
 
     } 
 
    } 
 
    
 
console.log(docs);
を試してみました

は私がfilterとを使用して、このオブジェクトこれは非常に簡単であるだけ

{"Id":2,"Name":"Second","Exam":[{"Pass":"Yes"},{"Sub":"T2"} 
+0

あなたは少し間違って 'splice'を使用している – KarelG

答えて

2

でのみドキュメントを必要とします:

docs = docs.filter(doc => doc.Exam.some(exam => exam.Pass === 'Yes')) 
+0

オムを、No''(要件'にYes''を ' '置き換える: ": "NO」パス" を持っている_Exam" _ ") – KarelG

+0

が必要ですが、彼の必要なものの例では"はい "です – Edwin

+0

@ KarelGいいえ、問題は*渡されていない試験を取り除くことです。 – str

0
const isExamPassed = exam => exam.Pass === 'Yes'; 

1. docs.filter(doc => isExamPassed(doc.Exam[0])); 
2. docs.map(doc => doc.Exam[0]) 
     .filter(isExamPassed); 
0

使用Array.filter API。

var docs = [{ 
 
    "Id": 1, 
 
    "Name": "First", 
 
    "Exam": [{ 
 
     "Pass": "No" 
 
    }, { 
 
     "Sub": "T1" 
 
    }] 
 
    }, 
 
    { 
 
    "Id": 2, 
 
    "Name": "Second", 
 
    "Exam": [{ 
 
     "Pass": "Yes" 
 
    }, { 
 
     "Sub": "T2" 
 
    }] 
 
    }, 
 
    { 
 
    "Id": 3, 
 
    "Name": "Third", 
 
    "Exam": [{ 
 
     "Pass": "No" 
 
    }, { 
 
     "Sub": "T3" 
 
    }] 
 
    } 
 
]; 
 

 
console.log("Before Filtering: ", docs.length); 
 
docs = docs.filter(function(doc, index) { 
 
    var bIsPass = true; 
 
    for (var j = doc.Exam.length - 1; j >= 0; --j) { 
 
    if (doc.Exam[j].Pass === "No") { 
 
     bIsPass = false; 
 
     break; 
 
    } 
 
    } 
 
    return bIsPass; 
 
}); 
 

 
console.log("Before Filtering: ", docs.length); 
 
console.log("Result :", docs);