我有一个问题,如何使用离子搜索栏来过滤嵌套JSON对象中的项目。由于我试图过滤header
项,因此它工作得很好,但它不适用于name
内的brands
换行。
{
"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
。
答案 0 :(得分:1)
您的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;
})