我有一个数组中的项目列表。数组中的每个元素包含以下内容:
id
date
status
name
description
我正在尝试创建第二个数组,其中包含第一个数组中状态=“待处理”的所有元素。
我正在我的 home.ts 文件中执行以下代码:
showPending(){
this.pendingItems = this.items;
this.pendingItems.filter((item) => {return item.status === 'pending'});
this.navCtrl.push(ShowPendingPage, {
pendingItems: this.pendingItems
});
}
当我运行应用程序时,我将 3 个元素添加到 items 数组中。 2 个元素的状态为待处理,1 个元素的状态为完成。当我执行上面的代码时,ShowPendingPage 被推送。我在 ShowPendingPage.ts 文件中执行以下代码:
this.passedArray = this.navParams.get('pendingItems')
我在 ShowPendingPage.html 中执行以下命令:
<ion-content>
<ion-list>
<ion-item-sliding *ngFor="let item of passedArray">
<ion-item [ngClass]="item.status">
{{item.name}} - Added {{item.date}}
</ion-item>
<ion-item-options side="right">
<button ion-button color="light" (click)="viewItem(item)">View</button>
</ion-item-options>
</ion-item-sliding>
</ion-list>
</ion-content>
结果数组包含原始数组的所有 3 个元素。它应该只包含 2 个元素,我将这两个元素的状态设置为待处理。
有谁比我有更好的眼睛,可以看到我所缺少的东西吗?
最佳答案
Array.prototype.filter
使用过滤后的元素创建一个新数组,但未就位。
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
还有
filter() does not mutate the array on which it is called.
您只需将其设置为变量即可。
this.pendingItems = this.pendingItems.filter((item) => {return item.status === 'pending'});
关于javascript - ionic 阵列过滤器不过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50519808/