如果存在嵌套对象数组,如何在Angular组件中使用数据过滤?

时间:2019-05-08 20:31:54

标签: angular

我想根据此YouTube教程视频为我的项目创建即时搜索功能。您可以找到书面版本here

使用以下JSON结构(同一教程系列使用),一切都可以正常工作:

[
 0: {
  id: 123,
  firstName: "Jon",
  lastName: "Doe",
  ...
 },
 1: {
  id: 321,
  firstName: "Tom",
  lastName: "Someone",
  ...
 }
]

但是我需要在项目中使用以下JSON结构,但无法修改(通过REST API获取):

[
 0: {
  employee: {
    id: 123,
    firstName: "Jon",
    lastName: "Doe",
    ...
  },
  someOtherObject: {
    key1: value1,
    key2: value2,
    ...
  },
  anotherObject: {
    ...
  }  
 },
 1: {
   employee: {
    id: 321,
    firstName: "Tom",
    lastName: "Someone",
    ...
  },
  someOtherObject: {
    key1: value1,
    key2: value2
  },
  anotherObject: {
    ...
  }  
 },
]

搜索功能不适用于上述JSON结构。

我想以相同的即时搜索体验搜索大多数嵌套对象。

更新:

employee.component.ts类似于linked指南。

employee.ts如下:

export class Document {
    _id: string;
    _rev: string;
    employee: any[];
    otherArray: any[];
    anotherArray: any[];
}

html看起来像这样:

<div *ngFor="let employee of filteredEmployees">
    {{ employee.firstName + ' ' + employee.lastName }}
</div>

1 个答案:

答案 0 :(得分:0)

使用管道

结合文本输入,一些模型绑定和管道,您应该能够实现我认为的目标。

在HTML

<input id="filter_input" type="text" [value]="filterBy" placeholder="Filter by {{filterOnText}}" (input)="filterBy = $event.target.value">

<div *ngFor="let employee of filteredEmployees | filter:filterOnKey:filterBy ">
    {{ employee.firstName + ' ' + employee.lastName }}
</div>

然后在组件中

filterOnText: string;
filterOnKey: string;
filterBy = '';

然后是管道

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'filter',
    pure: false
})
export class FilterPipe implements PipeTransform {

/*____________________________________________________________
* usage: *ngFor="let license of licenses  | filter:'Name':filterBy;
* 'Name' is the name of the column in list.
* filterBy obtained from input box
*_____________________________________________________________
*/
transform(items: any, property: any, term: any): any {
    if (!term) {
        return items;
    }

    const result = items.filter(function (item) {           

            if (item[property] === null) {
                return items;
            }
            if (item[property].toString().toLowerCase().includes(term.toLowerCase())) {
                return true;
            }
            return false;
        });
        if (result.length === 0) {
            return [-1];
        }
        return result;
    }
}