我有一个像这样的数组:
subjectWithTopics = [
{subjectName:"maths", topicName : "topic1 of maths " },
{subjectName:"maths", topicName : "topic2 of maths " },
{subjectName:"English", topicName : "topic1 of English " },
{subjectName:"English", topicName : "topic2 of English " },
{subjectName:"English", topicName : "topic3 of English " },
]
我想要的是在angular中使用* ngFor遍历此数组:
数学:
数学主题1
数学主题2
英语
英语主题1
英语主题2
英语主题3
所需数组:
subjectWithTopics =[
{"SubjectName" : "Maths",
"topicName" : [
{
topic1 of maths
},
{
topic 2 of maths
},
]
},
{"SubjectName" : "English",
"topicName" : [
{
topic 1 of English
},
{
topic 2 of English
},
{
topic 3 of English
}
]
}
]
答案 0 :(得分:2)
可以借助Array.prototype.reduce方法轻松完成此操作:
ts
subjectWithTopics = [
{ subjectName: "maths", topicName: "topic1 of maths " },
{ subjectName: "maths", topicName: "topic2 of maths " },
{ subjectName: "English", topicName: "topic1 of English " },
{ subjectName: "English", topicName: "topic2 of English " },
{ subjectName: "English", topicName: "topic3 of English " },
];
desiredResult: { SubjectName: string; topics: any[] }[];
ngOnInit() {
const groups = this.subjectWithTopics.reduce((acc, cur) => {
(acc[cur.subjectName] = acc[cur.subjectName] || []).push(cur.topicName);
return acc;
}, {});
this.desiredResult = Object.keys(groups).map(key => ({ SubjectName: key, topics: groups[key] }))
}
html
<ul *ngFor="let item of desiredResult">
<li>
{{ item.SubjectName }}
<ol>
<li *ngFor="let topic of item.topics">
{{ topic }}
</li>
</ol>
</li>
</ul>