简体   繁体   English

如何在 Ionic v5 中搜索和过滤数组?

[英]How to search and filter on an array in Ionic v5?

currently I'm trying to filter and search an array in Ionic v5.目前我正在尝试过滤和搜索 Ionic v5 中的数组。 But I don't know how to combine these two criteria.但我不知道如何结合这两个标准。

I have a page (room-overview), which displays all objects of a room-array.我有一个页面(房间概述),它显示房间阵列的所有对象。 I get these objects from a "data service", which reads a JSON file.我从读取 JSON 文件的“数据服务”中获取这些对象。

Part of the room-overview.ts-file: room-overview.ts-文件的一部分:

ionViewDidEnter() {
    this.setSearchedItems('');

    this.searchControl.valueChanges
      .pipe(debounceTime(300))
      .subscribe(search => {
        this.searching = false;
        this.setSearchedItems(search);
      });
  }

  onSearchInput() {
    this.searching = true;
  }

  setSearchedItems(searchTerm) {
    this.rooms = this.dataService.searchItems(searchTerm);
  }

On the room-overview page, there is a search bar, which can be used to search the individual objects.在房间概览页面上,有一个搜索栏,可用于搜索各个对象。 This search bar calls the onSearchInput()-method.此搜索栏调用 onSearchInput() 方法。

<ion-searchbar [formControl]="searchControl (ionChange)="onSearchInput()">

For that, I have a filter/search-service that gives me all objects which fits the search term.为此,我有一个过滤器/搜索服务,它为我提供所有适合搜索词的对象。 "items" is an array of all room-objects. “items”是所有房间对象的数组。

  searchItems(searchTerm) {
    return this.items.filter(item => {
      return item.name.toLowerCase().indexOf(searchTerm.toLowerCase()) > -1;
    });
  }

Besides the search, it should be possible to filter by certain criteria (for example, whether a room is in a certain building or not).除了搜索之外,还应该可以按某些标准进行过滤(例如,房间是否在某个建筑物中)。 This filter possibility is solved via a modal page that passes the values to the room-overview page when it will be closed.这种过滤器的可能性是通过一个模式页面来解决的,该页面将值传递给房间概览页面,当它关闭时。

Either the search or the filtering can be done individually, but I do not know how to combine both.搜索或过滤都可以单独完成,但我不知道如何将两者结合起来。 I think the "searchItem()"-method should not only filter on the room-object array.我认为“searchItem()”方法不应该只过滤房间对象数组。 It should be able to filter before and use only the filtered array.它应该能够在之前过滤并仅使用过滤后的数组。

I hope someone can help me:-)我希望有一个人可以帮助我:-)

Perhaps something like this?也许是这样的?

  searchAndFilterItems(searchTerm) {
        const filteredItems = this.items.filter(item => {
            // Apply filters
        });
        return filteredItems.filter(item => {
          return filteredItems.name.toLowerCase().indexOf(searchTerm.toLowerCase()) > -1;
        });
      }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM