创建具有相似键的新数组

create new array with similar key

我有一个这样的数组:

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 循环遍历这个数组:

所需数组:

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
          }
        ]
}
]

借助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>

Ng-run Example