Ionic数组过滤不生效求助:如何筛选status为pending的元素
Hey there, let's figure out why your filtered array isn't working as expected!
The core issue here is how JavaScript's Array.filter() works—it doesn't modify the original array, instead it returns a brand new array with only the items that match your condition. In your code, you're calling filter but never assigning its result back to this.pendingItems, so you're still passing the full original array to your next page.
Let's break down your problematic code:
showPending(){ this.pendingItems = this.items; this.pendingItems.filter((item) => {return item.status === 'pending'}); this.navCtrl.push(ShowPendingPage, { pendingItems: this.pendingItems }); }
- First line:
this.pendingItems = this.itemsjust makespendingItemspoint to the same array asitems—they're references to the exact same data in memory. - Second line: You run
filterwhich creates a new array with only pending items, but you don't save that new array anywhere.pendingItemsstill refers to the original full array.
The Fix
Simply assign the result of filter directly to this.pendingItems—you don't need to copy the original array first:
showPending(){ this.pendingItems = this.items.filter(item => item.status === 'pending'); this.navCtrl.push(ShowPendingPage, { pendingItems: this.pendingItems }); }
If you want to be extra safe (to avoid accidentally modifying the original items array later), you can create a shallow copy first before filtering:
showPending(){ // Create a copy of the original array, then filter this.pendingItems = [...this.items].filter(item => item.status === 'pending'); this.navCtrl.push(ShowPendingPage, { pendingItems: this.pendingItems }); }
Now when you pass pendingItems to ShowPendingPage, it'll only contain the 2 items with status: 'pending' like you expect.
Quick Note
Remember that filter, map, and reduce are all "pure" array methods—they never change the original array, always return a new one. It's easy to forget to capture that return value, but that's exactly what tripped you up here!
内容的提问来源于stack exchange,提问作者Jonathan Small

