2017-08-11 69 views
3

我想基於使用兩種過濾方法的字符串過濾對象內的數組。這是我的對象的樣子。使用自動完成功能在對象內過濾數組

[ 
    { 
    "cat": "Accommodation and Food Service Activities", 
    "value": [ 
     { 
     "sic": "55", 
     "desc": "Accommodation" 
     }, 
     { 
     "sic": "56", 
     "desc": "Food and beverage service activities" 
     } 
    ] 
    }, 
    { 
    "cat": "Activities Of Extraterritorial Organisations and Bodies", 
    "value": [ 
     { 
     "sic": "99", 
     "desc": "Activities of extraterritorial organisations and bodies" 
     } 
    ] 
    } 
] 

我想過濾的value.desc並返回cat

這裏是我迄今爲止

filteredIndustries(industry: string) { 
    if (industry) { 
     return this.industries.filter(sector => { 
     if (sector.value) { 
      sector.value.findIndex(v => { 
      return v.desc.toString().toLowerCase().indexOf(industry.toString().toLowerCase()) === 0; 
      }); 
     } 
     }); 
    } else { 
     return this.industries; 
    } 

,這裏是我的html,

<md-input-container> 
     <input mdInput placeholder="Industry" [mdAutocomplete]="auto" [formControl]="industryCtrl"> 
    </md-input-container> 

    <md-autocomplete #auto="mdAutocomplete" [displayWith]="displayIndustry.bind(this)"> 
     <md-option *ngFor="let industry of filteredIndustry | async" [value]="industry"> 
     {{ industry.cat }} 
     </md-option> 
    </md-autocomplete> 

所以當我輸入食物時,它應該過濾value.desc並返回cat這應該是Accommodation and Food Service Activities

但我沒有得到,即使我的返回結果爲true的返回值。

任何幫助將不勝感激。

+0

歡迎SO!這是一個很好的第一個問題,您發佈了代碼並正確解釋了您的問題,使您可以輕鬆地爲您提供幫助。 +1 –

回答

1

您的filter回調函數未命中返回語句,如果findIndex返回大於-1的東西,則應返回true;

filteredIndustries(industry: string) { 
    if (industry) { 
     return this.industries.filter(sector => { 
     if (sector.value) { 
      return -1 < sector.value.findIndex(v => { //HERE 
      return v.desc.toString().toLowerCase().indexOf(industry.toString().toLowerCase()) === 0; 
      }); 
     } 
     }); 
    } else { 
     return this.industries; 
    } 
} 
+1

這只是你傳遞給filter()的函數總是返回undefined,它是一個「falsy」值,所以它過濾掉了數組中的所有元素this.industries –

+0

感謝您的幫助,這幫助我得到它工作。 – Ergun

0

可以使用some()代替findIndex()indexOf如果未找到指定的字符串,則返回-1。

var industries = [ 
 
    { 
 
    "cat": "Accommodation and Food Service Activities", 
 
    "value": [ 
 
     { 
 
     "sic": "55", 
 
     "desc": "Accommodation" 
 
     }, 
 
     { 
 
     "sic": "56", 
 
     "desc": "Food and beverage service activities" 
 
     } 
 
    ] 
 
    }, 
 
    { 
 
    "cat": "Activities Of Extraterritorial Organisations and Bodies", 
 
    "value": [ 
 
     { 
 
     "sic": "99", 
 
     "desc": "Activities of extraterritorial organisations and bodies" 
 
     } 
 
    ] 
 
    } 
 
] 
 

 
var industry = 'food' 
 
var b = industries.filter(sector => { 
 
    if (sector.value) { 
 
    return sector.value.some(v => v.desc.toLowerCase().indexOf(industry) >= 0); 
 
    } else { 
 
    return industries 
 
    } 
 
}); 
 

 
console.log(b)

+0

不幸的是,這並沒有返回一個值。不管怎麼說,還是要謝謝你。整理出 – Ergun

+1

我編輯了我的答案,以證明我的代碼有效。 – kulaeff