2017-02-24 43 views
0

我卡在我的打字稿過濾器函數中。通過另一個字符串數組對象打印字符過濾器數組

我有對象的數組:

[ 
    { 
    "id": 12345, 
    "title": "Some title", 
    "complexity": [ 
     { 
     "slug": "1" // my search term 
     "name": "easy" 
     }, { 
     "slug": "2" // my search term 
     "name": "middle" 
     }, 
{...} 

而且我有一個字符串與被許可的複雜陣列:

public allowedComplexityArray:Array<string> = ["1"]; 

我的任務:我只想顯示與對象允許「1」的複雜性。

但不知何故,我的功能不工作,我不知道爲什麼:

allowedMeals = meals.filter(meal => { 
    return meal.complexity.every(complexityObj => that.allowedComplexityArray.indexOf(complexityObj.slug) > -1) 
}); 

回答

1

嘗試:

let allowedMeals = data.filter(meal => { 
    return meal.complexity.findIndex(complexityObj => 
     allowedComplexityArray.findIndex(m => m == complexityObj.slug) > -1) > -1 
}); 

我的return子句中使用的findIndex代替filter所以它並不需要每次掃描整個陣列。

相關問題