根据打字稿中的属性对对象数组进行排序

问题描述:

我正在表中显示一个数组,其中包含"request"类型的项目.我想对表的列进行排序,所以我计划为每个列标题创建一个click方法.该方法根据该列中显示的属性的值对数组进行排序.

I'm showing an array with items of type 'request' in a table. I want to sort the columns of the table so I planned to make a click method for every column header. This methods sorts the array based on the value of the property shown in that column.

public sortProduct(): void {

    this.requests.sort((a, b) => {
        if (a.productName < b.productName)
            return -1;
        if (a.productName > b.productName)
            return 1;
        return 0;
    });

    if (!this.productSortOrder) {
        this.requests.reverse();
        this.productSortOrder = true;
    } else {
        this.productSortOrder = false;
    }        
}   

这行得通,但是现在我需要为每一列创建一个方法.我正在寻找一种调用像这样的排序方法的方法:

This works, but now I need to make a method for every column. I am looking for a way to call a sort method like this:

this.requests.sortMethod(property, order);

然后,此方法将根据数组中对象的属性以及给定的排序顺序对请求数组进行排序. 我怎样才能做到这一点?我想我正在C#中寻找像Func<>之类的东西.

This method would then sort the requests array based on the property of the objects in the array and in the given sortorder. How can I do that? I guess I'm looking for something like Func<> in C#.

您可以使用函数签名来获得与Func

You can us a function signature for a similar effect to Func

sortProduct<T>(prop: (c: Product) => T, order: "ASC" | "DESC"): void {
    this.requests.sort((a, b) => {
        if (prop(a) < prop(b))
            return -1;
        if (prop(a) > prop(b))
            return 1;
        return 0;
    });

    if (order === "DESC") {
        this.requests.reverse();
        this.productSortOrder = true;
    } else {
        this.productSortOrder = false;
    }        
}
// Usage
sortProduct(p=> p.productName, "ASC");

或者您也可以使用属性名称(keyof Product将确保字符串必须是Product的属性):

Or you can use the property name instead (keyof Product will ensure the string must be a property of Product):

sortProduct<T>(propName: keyof Product, order: "ASC" | "DESC"): void {
    this.requests.sort((a, b) => {
        if (a[propName] < b[propName])
            return -1;
        if (a[propName] > b[propName])
            return 1;
        return 0;
    });
    ...
} 
// Usage
sortProduct("productName", "ASC");
sortProduct("productName_", "ASC"); // Error