如何在 Aurelia/Typescript 中根据嵌套属性对对象数组进行排序
我必须按对象的嵌套属性对数组进行排序。更准确地说,我必须根据 payment.paymentDate 属性对从 service.payments 对象派生的 payment 进行排序。
有没有办法自定义排序转换器代码或修改 HTML,这样我就可以根据 paymentDate 对付款进行排序?
详情请参见下面的代码:
这是 HTML 代码:
<ul>
<li repeat.for="payment of service.payments | sort:payment.paymentDate:'ascending'">
${'dashboard:contracts.desc.custPayment' & t: {
value: payment.value,
currency: payment.currency,
date: formatDate(payment.paymentDate)
}}
</li>
</ul>
这是我的 SortValueConverter 代码:
export class SortValueConverter {
toView(array: {}[], property: string, direction: string) {
let sorted = [].slice.call(array).sort((a, b) => {
if (a[property] > b[property]) return 1;
if (a[property] < b[property]) return -1;
return 0;
});
return direction === 'ascending' ? sorted : sorted.reverse();
}
}
这是数据:
答案#1
根据你下面提供的 sort valueConverter,你的 HTML 应该如下所示:
<li repeat.for="payment of service.payments | sort:'paymentDate':'ascending'">
${'dashboard:contracts.desc.custPayment' & t: {
value: payment.value,
currency: payment.currency,
date: formatDate(payment.paymentDate)
}}
</li>
还有:为什么不直接常规使用数组排序函数呢?
export class SortValueConverter {
toView(arr: any[], property: string, direction: string) {
const sorted = arr.sort((a, b) => a[property] - b[property]));
return direction === 'ascending' ? sorted : sorted.reverse();
}
}
