【发布时间】:2020-02-08 13:28:21
【问题描述】:
我通过有角度的 HttpClient Observable 将该对象返回给我。
{
"jsonrpc": "2.0",
"result": [
{
"event": {
"id": "29688772",
"name": "Demoliner/Middelkoop v Behar/Escobar",
"countryCode": "AR",
"timezone": "UTC",
"openDate": "2020-02-08T20:00:00.000Z"
},
"marketCount": 1
},
{
"event": {
"id": "29691591",
"name": "Bemelmans v Pellegrino",
"countryCode": "FR",
"timezone": "UTC",
"openDate": "2020-02-09T09:00:00.000Z"
},
"marketCount": 1
},
{
"event": {
"id": "29690566",
"name": "Diez v Emil Ruusuvuori",
"countryCode": "NL",
"timezone": "UTC",
"openDate": "2020-02-08T13:14:00.000Z"
},
"marketCount": 1
},
{
"event": {
"id": "29690822",
"name": "Koepfer v J Rodionov",
"countryCode": "US",
"timezone": "UTC",
"openDate": "2020-02-08T18:00:00.000Z"
},
"marketCount": 1
},
{
"event": {
"id": "29691586",
"name": "Basic v Vanni",
"countryCode": "FR",
"timezone": "UTC",
"openDate": "2020-02-09T09:00:00.000Z"
},
"marketCount": 1
},
{
"event": {
"id": "29691596",
"name": "P Kotov v Mayot",
"countryCode": "FR",
"timezone": "UTC",
"openDate": "2020-02-09T09:00:00.000Z"
},
"marketCount": 1
}
我想按 openDate 对数组进行排序。
我想在订阅中这样做
getTennisMatches() {
this.betfairService.getTennisMatches().subscribe((data: any[]) => {
this.matches = data;
this.sortedMatches = this.matches.sort((a, b) => (a.result.event.openDate > b.result.event.openDate) ? 1 : -1);
// OR
this.sortedMatches = _.sortBy(this.matches.result, o => o.result.event.openDate);
});
}
两种排序方法都不能处理错误
this.matches.sort is not a function 香草或
Cannot read property 'event' of undefined 为 lodash
我认为我必须迭代事件,但我不确定我在做什么。我使用 lodash 是因为我发现它的语法更容易理解,但我不必使用它。谢谢
【问题讨论】:
-
数组是
this.matches.result,而不是this.matches。而且您的排序比较器函数应该返回一个数字,而不是布尔值。 -
感谢您的快速回复。我以为它返回的是一个 1 或负 1 的数字。抱歉,我有点困惑。
-
1.它不返回
1或-1,而是返回1或0。 2. 即使这样,您也必须返回 三个 值,而不是两个。了解两个项目是否相等 很重要。 Sorting in JavaScript: Shouldn't returning a boolean be enough for a comparison function?
标签: javascript angular lodash