json数据,
{
"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"
}
]
}
我需要分组在#34; country"然后分组"州"那么" city"。
我的打字稿界面,
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 :(得分:1)
这不是帮助,而是请求......无论如何它是:
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;
}, {});
}
现在你有了一个分组对象。您可以使用它,也可以将其转换为数组。