[英]How to sort the array of objects based on nested property in Aurelia/Typescript
[英]Sort array of objects based on property in typescript
我正在表中显示一个包含'request'类型项的数组。 我想对表的列进行排序,因此我计划为每个列标题创建一个click方法。 此方法根据该列中显示的属性值对数组进行排序。
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.requests.sortMethod(property, order);
然后,此方法将根据数组中对象的属性和给定的排序顺序对请求数组进行排序。 我怎样才能做到这一点? 我想我正在寻找像C#中的Func <>之类的东西。
你可以使用函数签名来获得与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
的属性):
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
您可以将SortUtil类与静态模板方法sortByProperty一起使用:
export class SortUtil {
static sortByProperty<T>(array: T[], propName: keyof T, order: 'ASC' | 'DESC'): void {
array.sort((a, b) => {
if (a[propName] < b[propName]) {
return -1;
}
if (a[propName] > b[propName]) {
return 1;
}
return 0;
});
if (order === 'DESC') {
array.reverse();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.