角2(打字稿) - RxJS可观察到的 - GROUPBY

问题描述:

JSON数据,角2(打字稿) - RxJS可观察到的 - GROUPBY

{ 
"name": "Sam", 
"age":25, 
"schools": 
[ 
    { 
     "country":"USA", 
     "state":"IN", 
     "city":"Fishers", 
     "name":"school 1" 
    }, 
    { 
     "country":"USA", 
     "state":"IN", 
     "city":"Indianapolis", 
     "name":"school 2" 
    }, 
    { 
     "country":"USA", 
     "state":"CO", 
     "city":"Denver", 
     "name":"school 3" 
    }, 
    { 
     "country":"Canada", 
     "state":"Ontario", 
     "city":"Toronto", 
     "name":"school 4" 
    } 
    ] 
} 

我需要组通过对学校阵列上的“国家”,然后按“状态”,然后“城市”。

我的打字稿接口,

interface Person{ 
name:string; 
age:number; 
schools: School[]; 
} 

interface School{ 
country:string; 
states: State[]; 
} 

interface State{ 
state:string; 
pairs: Pair[]; 
} 

interface Pair{ 
city:string; 
name:string; 
} 

我需要写一个服务方法,让学校按国家和国家分组由国家分组,各城市和名称分组到JSON数据转换到我的模型。

是我的模型结构是否正确?如果是这样,我怎么根据我的需要做分组。

我的服务方法看起来应该像这样的事情,

getPerson():Observable<Person> 
{ 
     return this.http.get(url to get json data).groupBy(XYZ..)..... 
} 
+0

的可能的复制[如何GROUPBY上一个HTTP响应?](https://*.com/questions/43096470/how-do-i-groupby-on-a-http-response) – mxr7350

这不是帮忙,而是请求...反正这里是:

groupBy(array: any[], property: string) { 
    return array.reduce((prev, next) => { 
     // If the group doesn't exist, create it 
     if(!prev[property]) { prev[property] = [next]; } 
     // Else, we push it in 
     else { prev[property].push(next); } 
     // Mandatory return 
     return prev; 
    }, {}); 
} 

现在你有一个分组目的。您可以使用它,也可以将其转换为数组。