在TypeScript中基于string值属性对对象进行sorting

我有一个对象的数组,对象的定义如下所示:

export class AccountInfo { accountUid: string; userType: string; firstName: string; middleName: string; lastName: string; } 

注意:我没有userType作为枚举的原因是因为该对象是由数据库调用填充,我不能找出一个干净的方式,从数据库返回的string填充枚举。

我想对数组进行sorting,使得userType为'STAFF'的对象先出现,然后是“TEACHER”,然后是“PARENT”,然后是“STUDENT”。

您可以将订单存储在array ,然后使用indexOf进行sort来实现您的目标。 看下面的代码示例:

 let humans = [{ accountUid: "1", userType: "TEACHER", }, { accountUid: "2", userType: "STAFF", }, { accountUid: "3", userType: "STUDENT", }, { accountUid: "4", userType: "PARENT", }]; let order = ['STAFF', 'TEACHER', 'PARENT', 'STUDENT']; const result = humans.sort((a, b) => order.indexOf(a.userType) > order.indexOf(b.userType)); console.log(result)