I have a Leaf class that I want to use to convert all nodes in a JSON response into instances of Leaf. The structure of the JSON response is as follows:
JSON Response
{
"name":"animal",
"state":false,
"children":[
{
"name":"cats",
"state":false,
"children":[
{
"name":"tiger",
"state":false,
},
{
"name":"puma",
"state":false,
"children":[
{
"name":"babyPuma",
"state":true
}
]
}
]
},
{
"name":"dogs",
"state":false,
"children":[
{
"name":"pitbull",
"state":true
},
{
"name":"german",
"state":false,
"children":[
{
"name":"shepherd",
"state":true
}
]
}
]
}
]
}
I am using observables to fetch this data and have successfully cast the first node:
http.service.ts snippet
getTreeData(): Observable<Leaf>{
var headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.post('http://localhost:8000/',{ headers: headers ...})
.map(res =>new Leaf(res.json()));
}
Here's the Leaf class implementation:
Leaf.ts
export class Leaf{
name: string;
state: string;
treeData: Array<Leaf>;
constructor(input:any){
this.name = input.name;
this.state = input.state;
this.treeData = input.children;
}
toggleState() {
if (this.state=='active'){
this.state = 'inactive';
}
else {
this.state = 'active'
}
}
}
My end goal is to display the JSON tree in a folder-like structure. Is there a way to traverse through all nodes using map(), or do I need to implement a different approach involving a combination of map() and a traverser function?