0

json data,

{
 "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"
     }
   ]
}

I need to group by on schools array on "country" then group by "state" then "city".

My typescript interface,

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;
}

I need to write a service method to transform a json data to my model so that schools grouped by country and countries grouped by state and states grouped by city and name.

Is my model structure correct? If so, how can i do group by according to my need.

My service method should look like something like this,

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

1 Answer 1

1

This isn't help, but a request ... Anyways here it is :

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;
    }, {});
}

Now you have a grouped object. You can either use it, or transform it into an array.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.