【问题标题】:create new array with similar key [duplicate]创建具有相似键的新数组[重复]
【发布时间】:2020-11-15 15:40:54
【问题描述】:

我有一个这样的数组:

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

【问题讨论】:

    标签: arrays angular typescript angular8 ngfor


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-06
      • 1970-01-01
      • 2022-07-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-07
      • 2018-02-15
      • 1970-01-01
      相关资源
      最近更新 更多