我通过一个有角度的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
for lodash
我认为我必须对事件进行迭代,但是我不确定自己在做什么。我使用lodash是因为我发现它的语法更容易理解,但我不必使用它。谢谢
答案 0 :(得分:1)
您可以对对象内部的matches
数组进行排序,而不是对result
对象进行排序。
this.matches.result.sort((a, b) => Date.parse(a.event.openDate) - Date.parse(b.event.openDate));
但是请注意,这也会对原始对象进行排序。
简化示例片段:
let matches = {
result : [
{ id:1001 , event: { openDate : "2020-02-03T20:00:00.000Z" } },
{ id:1002 , event: { openDate : "2020-02-01T20:00:00.000Z" } },
{ id:1003 , event: { openDate : "2020-02-03T20:00:00.000Z" } },
{ id:1004 , event: { openDate : "2020-02-04T20:00:00.000Z" } },
{ id:1005 , event: { openDate : "2020-02-02T20:00:00.000Z" } }
]
};
let sorted = matches.result.sort((a, b) => Date.parse(a.event.openDate) - Date.parse(b.event.openDate));
console.log('original object after sort', JSON.stringify(matches));
答案 1 :(得分:0)
this.matches.sort is not a function
表示您的变量this.matches
为空,并且您正在尝试对其进行迭代,因此首先必须检查MS调用的响应。可以检索一个空数组。
类型而不是'any'将对您的建议很有帮助,以检查它是否可以正常工作并检索一些数据,但它们没有预期的格式。
还可以在Chrome开发者工具中选中“网络”部分以查看响应。