Ionic 3 过滤器嵌套 JSON 与 ionic 搜索栏

Ionic 3 filter nested JSON with ionic searchbar

我有一个问题如何使用离子搜索栏来过滤嵌套 JSON 对象中的项目。当我尝试过滤 header 项目时,它工作得很好,但它不适用于 brands.

内的 name 包装
{
"items": [{
        "header": "A",
        "brands": [{ "name": "Apple", "id": "1" }, { "name": "Adidas", "id": "2" }]
    },
    {
        "header": "B",
        "brands": [{ "name": "Bose", "id": "3" }, { "name": "Boss", "id": "4" }, { "name": "Birkenstock", "id": "5" }]
    },
    {
        "header": "M",
        "brands": [{ "name": "McDonalds", "id": "6" }]
    }
]
}

我的search.ts:

    private result: any[];
  private searchItems: any;
  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    private http: Http
  ) {
    let localData = this.http.get('assets/search-brand.json').map(res => res.json().items);
    localData.subscribe(data => {
      this.result = data;
    });
    this.initializeItems();
  }

  initializeItems() {
    this.searchItems = this.result;
  }

  getItems(ev: any) {
    // Reset items back to all of the items
    this.initializeItems();

    // set val to the value of the searchbar
    let val = ev.target.value;

    // if the value is an empty string don't filter the items
    if (val && val.trim() != '') {
      this.searchItems = this.searchItems.filter((item) => {
        return (item.header.toLowerCase().indexOf(val.toLowerCase()) > -1);
      })
    }
  }

我的代码(search.html):

<ion-searchbar (ionInput)="getItems($event)"></ion-searchbar>
<p>{{test}}</p>
<ion-list *ngFor="let item of searchItems; let i = index">
    <ion-list-header>
        {{item.header}}
    </ion-list-header>
    <ion-item *ngFor="let brands of item.brands; let j = index" (click)="selectedBrand(brands.id)">{{brands.name}}</ion-item>
</ion-list>

这个正在过滤 brands.name 它说 .toLowerCase() is not a function

您的 JSON 数据可能有一些元素具有 header == null 或没有 brands 属性。所以为了确保搜索正常工作,你应该通过 if 语句来处理这些情况。您需要重写过滤器函数以获得预期的输出。
试试这个:

this.searchItems = this.searchItems.map((item)=>{
   if(item && item.brands && item.brands.length > 0){
     item.brands = item.brands.filter(brand=>{
      if(!brand.name) return false;
      return brand.name.toLowerCase().indexOf(val.toLowerCase()) > -1;
     });
   }    
   retrun item;   
})