Angular Material 2 DataSource filter with nested object

前端 未结 3 1221
无人共我
无人共我 2020-12-28 15:14

I have angular 4 project with material 2, I want to filter the data in MatTable. DataSource filter is working fine when we filter data on field which are not nested.

<
3条回答
  •  萌比男神i
    2020-12-28 15:29

    Here is a solution that incorporates recursion so you don't have to hard code each nested object or their key/value pairs.

    this.dataSource.filterPredicate = (data, filter: string)  => {
      const accumulator = (currentTerm, key) => {
        return this.nestedFilterCheck(currentTerm, data, key);
      };
      const dataStr = Object.keys(data).reduce(accumulator, '').toLowerCase();
      // Transform the filter by converting it to lowercase and removing whitespace.
      const transformedFilter = filter.trim().toLowerCase();
      return dataStr.indexOf(transformedFilter) !== -1;
    };
    

    And the nestedFilterCheck

    nestedFilterCheck(search, data, key) {
      if (typeof data[key] === 'object') {
        for (const k in data[key]) {
          if (data[key][k] !== null) {
            search = this.nestedFilterCheck(search, data[key], k);
          }
        }
      } else {
        search += data[key];
      }
      return search;
    }
    

    Thanks to @Sagar Kharche for the filterPredicate override.

提交回复
热议问题