我需要一種方法來防止在角度模板中顯示重復的內容。我有一個資料陣列,其中一些資料共享相同的 formId。在我的模板中,我顯示了陣列的名稱,如果 formId 是唯一的,則在分隔線之后,但如果陣列共享相同的 formId,則直到 formId 更改后才會顯示分隔線。所以如果我有陣列:
[
{
id: 1,
name: 'Test 1'
formId: '8979f9879f'
},
{
id: 2,
name: 'Test 2'
formId: '8979f9879f'
},
{
id: 3,
name: 'Test 3'
formId: 'a8098981'
},
]
The result should be:
Test 1
Test 2
_______
Test 3 ... and so on
The ones that share the same formId, I need to put in the same table layout, so I needed to group the data with same formId, getting the result like this:
[
8979f9879f: [
{
id: 1,
name: Test 1,
formId: 8979f9879f
},
{
id: 2,
name: Test 2,
formId: 8979f9879f
},
],
a8098981: [
{
id: 3,
name: Test 3,
formId: a8098981
}
]
]
Which is fine. But now in a template when I loop though this arrays:
<ng-container *ngFor="let formItem of formListItems | async, index as i">
<div *ngFor="let groupedItem of groupedFormListItems[formItem.formId]" ...
我得到了正確的布局和結果,只有我得到了重復的結果,因為嵌套回圈。所以頁面上的布局如下所示:
測驗 1 測驗 2
測驗 1 測驗 2
測驗 3
我需要以某種方式檢查 formId 是否已經回圈,但不知道該怎么做。
uj5u.com熱心網友回復:
您需要對陣列進行更好的操作,以便您可以將相同的 formId 測驗組合在一起,但也可以通過ngFor. 這是一個快速而骯臟的解決方案。

uj5u.com熱心網友回復:
您可以使用“reduce”對元素進行分組
this.processFormData=this.formList.reduce((a:any,b:any)=>{
const element=a.find(x=>x.formId==b.formId)
if (element)
element.items.push(b)
else
a.push({formId:b.formId,items:[b]})
return a;
},[])
注意:reduce 回傳一個陣列,如果你想遍歷它,回傳一個 abject 是沒有意義的
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/535095.html
