![](/img/trans.png)
[英]Creating a dynamic item list and display the the item as per user subscription
[英]How to display one item per `type` attribute in a list?
我正在編寫一個 Angular 8 應用程序。 在其中一個視圖中,可以選擇顯示Product
類的項目列表,並且可以通過多種方式過濾此列表。
export class Product {
constructor(
public id: number,
public type: number
) {
}
}
我想做的事:
在Product
的屬性中有type
。 我如何過濾它們才能獲得每種類型的項目? 我會做的是使用這個函數,但我不知道如何在括號中編寫邏輯語句。
filterItemsOnePerType() {
this.filteredProducts = Object.assign([], this.products).filter(
item => (... item.type ...)
);
}
請注意,將要選擇的項目並不重要。 重要的是,在最終視圖中,我不會看到類型之間有任何重復。
例子
我有一個產品清單:
[{id: 1, type:1},
{id: 2, type:1},
{id: 3, type:1},
{id: 4, type:2},
{id: 5, type:2},
{id: 6, type:3},
{id: 7, type:2}]
因此,我想獲得的是以下列表:
[{id: 1, type:1},
{id: 4, type:2},
{id: 6, type:3}]
this.filteredProducts = Object.assign([], this.products).filter(
(types => item => !types.has(item.type) && types.add(item.type))(new Set)
);
您可能希望使用 Set 來排除重復項。
您可以使用Array.reduce
方法將其過濾掉。
const array = [ { id: 1, type: 1 }, { id: 2, type: 1 }, { id: 3, type: 1 }, { id: 4, type: 2 }, { id: 5, type: 2 }, { id: 6, type: 3 }, { id: 7, type: 2 } ]; const result = array.reduce((result, item) => { const isFound = result.find(({ type }) => item.type === type); if (isFound) { return result; } return [...result, item]; }, []); console.log(result);
回到您的原始代碼,您將執行以下操作:
filterItemsOnePerType() {
this.filteredProducs = Object.assign([], this.producs).reduce(
(result, item) => {
const isFound = result.find(
({ type }) => item.type === type
)
if (isFound) return result
return [...result, item]
}, []
)
}
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.