这里有example
基本上对象不是存储数组的好方法,更好地将其转换为具有如下结构的实际数组:
{ key: string, value: string }[]
这将使您能够使用数组过滤器并与 angular ngFor 平滑集成。
在组件中:
/** Fixed structure or some logic that will transform your data into it like for exampe reducer */
list = [
{ key: 'ab', value: 'a val' },
{ key: 'bc', value: 'baa' },
{ key: 'kk', value: 'try' },
{ key: 'dd', value: 'again' },
]
/** Search phrase that will be used for filtering your data set */
phrase$ = new BehaviorSubject<string>('');
/** Observable for filtering out data to show in table */
items$ = this.phrase$.pipe(
map((phrase = '') => phrase.length > 0
? this.list
.filter(({ value }) => value.indexOf(phrase) >= 0).slice(0)
: this.list
)
)
/** pushing new phrase values */
onChange(e) {
this.phrase$.next(e);
}
在模板中
Enter search phrase: <input (keyup)="onChange($event.target.value)">
<table>
<tr *ngFor="let item of items$ | async"><th>{{ item.key }}</th><td> {{ item.value }}</td></tr>
</table>
如果您需要将数据转换为数组的逻辑:
list = Object.entries(data).reduce((result, [key, value]) => {
result[key] = value;
return result;
}, {})