基于TypeScript中的字符串值属性对对象进行排序

Tov*_*ird 3 javascript enums node.js typescript

我有一个对象数组,对象的定义看起来像这样:

export class AccountInfo {
  accountUid: string;
  userType: string;
  firstName: string;
  middleName: string;
  lastName: string;
}
Run Code Online (Sandbox Code Playgroud)

注意:我没有将userType作为枚举的原因是因为对象是由数据库调用填充的,我无法找到一种干净的方法让db返回的字符串填充枚举.

我想对数组进行排序,以便首先显示userType为"STAFF"的对象,然后是"TEACHER",然后是"PARENT",然后是"STUDENT".

Dan*_*tir 8

您可以顺序存储在一个array,那么就使用indexOfsort来实现自己的目标.请参阅下面的代码示例:

const humans = [{
  accountUid: "1",
  userType: "TEACHER",
}, {
  accountUid: "2",
  userType: "STAFF",
}, {
  accountUid: "3",
  userType: "STUDENT",
}, {
  accountUid: "4",
  userType: "PARENT",
}];

const order = ['STAFF', 'TEACHER', 'PARENT', 'STUDENT'];

const result = humans.sort((a, b) => order.indexOf(a.userType) - order.indexOf(b.userType));

console.log(result)
Run Code Online (Sandbox Code Playgroud)

如果你不能使用ES6,只需使用:

humans.sort(function(a, b){
    return order.indexOf(a.userType) - order.indexOf(b.userType);
});
Run Code Online (Sandbox Code Playgroud)