首页 > 解决方案 > 如何对具有相同值的 HTML 表进行分组(Javascript)

问题描述

我有一个包含这样的约会数据的数组,我想从中制作表格:

[
 { 
  day: '20/10/2020',
  subject: 'meeting',
  client: 'Rob'
  location: 'Office
 },
{ 
  day: '21/10/2020',
  subject: 'meeting',
  client: 'Lisa'
  location: 'Town'
 },
{ 
  day: '21/10/2020',
  subject: 'meeting',
  client: 'Kevin'
  location: 'Office
 },
 { 
  day: '22/10/2020',
  subject: 'meeting',
  client: 'Kevin'
  location: 'Home'
 }
]

我的html文件:

 <div *ngFor="let appointment of appointments"   class="card-body">
   <table class="table table-striped">
     <thead>
  <tr>
  <th>  Day </th>
  <th>Where </th>
  <th> Client</th>
  <th>Subject</th>
  </tr>
  </thead>
  <tfoot>
  <tr>
  <td>  <small>{{appointment.day}}</small></td>
  <td> <small>{{appointment.location}} </small> </td>
  <td><small>{{appointment.client}}</small> </td>
    <td><small>{{appointment.subject}} </small></td>
  </tfoot>
</table>
</div>

这会为每个约会生成一个表格,但是我怎样才能使同一天的约会出现在彼此下方,而没有中间人。就像这样:(可视化)

在此处输入图像描述

任何帮助表示赞赏

标签: htmlarraysangularhtml-tablengfor

解决方案


有一个非常简单的方法可以解决您的问题,让我们来做吧。我们将使用lodash库,所以首先你需要导入。

通过 NPM 安装:

npm i lodash
npm i --save-dev @types/lodash

并导入我们的项目:

import * as _ from 'lodash';

那么神奇的事情发生了,我们刚刚导入的朋友和它的groupBy()方法:

let result = _.groupBy(this.appointments, (appointment) => {
return appointments.day;
});
console.log(result);

控制台的结果将是:

{
  "20/10/2020": [
    {
      "day": "20/10/2020",
      "subject": "meeting",
      "client": "Rob",
      "location": "Office"
    }
  ],
  "21/10/2020": [
    {
      "day": "21/10/2020",
      "subject": "meeting",
      "client": "Lisa",
      "location": "Town"
    },
    {
      "day": "21/10/2020",
      "subject": "meeting",
      "client": "Kevin",
      "location": "Office"
    }
  ],
  "22/10/2020": [
    {
      "day": "22/10/2020",
      "subject": "meeting",
      "client": "Kevin",
      "location": "Home"
    }
  ]
}

推荐阅读