将数据转换为另一种数据并在 table 上显示

Convert data to another and display it on table

您好,我正在 angular 9 上使用打字稿。我有一个如下所示的数据,我将把它显示在垫子上-table。

我如何转换它

0: CustomPoDTO {id: "1", equipmentOrdered: "Monitor, Keyboard", quantity: 2}
1: CustomPoDTO {id: "2", equipmentOrdered: "Keyboard, Monitor, Mouse", quantity: 6}
2: CustomPoDTO {id: "3", equipmentOrdered: "Mouse", quantity: 2}

到这个?

0: CustomPoDTO {id: "1", equipmentOrdered: "Monitor and 1 more", quantity: 2}
1: CustomPoDTO {id: "2", equipmentOrdered: "Keyboard and 2 more", quantity: 6}
2: CustomPoDTO {id: "3", equipmentOrdered: "Mouse", quantity: 2}

数数equipmentOrdered

const ar = [{id: "1", equipmentOrdered: "Monitor, Keyboard", quantity: 2},
            {id: "2", equipmentOrdered: "Keyboard, Monitor, Mouse", quantity: 6},
            {id: "3", equipmentOrdered: "Mouse", quantity: 2}]

ar.forEach((item) => {
   eq = item['equipmentOrdered'].split(',')
   if (eq.length > 1) {
     item['equipmentOrdered'] = `${eq[0].trim()} and ${(eq.length - 1)} more`
   }
   
})

console.log(ar);

您应该根据数据显示文本,例如 equipmentOrdered 带有管道的列,而不是修改数据。

<ng-container matColumnDef="equipmentOrdered">
  <th mat-header-cell *matHeaderCellDef>Equiment ordered</th>
  <td mat-cell *matCellDef="let item">{{ item.equipmentOrdered | displayMore }} </td>
</ng-container>
@Pipe({name: 'displayMore '})
export class DisplayMorePipe implements PipeTransform {
  transform(value: string): string {
    const [firstItem, ...others] = value.split(',');
    return others.length > 0 ? `${firstItem} and ${others.length} more` : firstItem;
  }
}

使用它获得所需的输出

  array.forEach(element => {
   const tempString = element.equipmentOrdered.split(',');
  let stringFormation = tempString[0];
  if(tempString.length > 1) {
    stringFormation = stringFormation + ' and ' + String(tempString.length-1) + ' more'
  }
  element.equipmentOrdered = stringFormation;
});

let orders = [
    {id: "1", equipmentOrdered: "Monitor, Keyboard", quantity: 2},
    {id: "2", equipmentOrdered: "Keyboard, Monitor, Mouse", quantity: 6},
    {id: "3", equipmentOrdered: "Mouse", quantity: 2}
];

orders.forEach(order => {
    if(order.equipmentOrdered.includes(',')){
        quantity = order.quantity -1;
        order.equipmentOrdered = order.equipmentOrdered.split(',').shift() + ' and ' + quantity+ ' more';
    }
});

console.log(orders)