如何将嵌套JSON树的所有节点转换为angular 2 Typescript中的类的实例?

时间:2016-11-01 18:12:22

标签: javascript json angular typescript

我有一个名为Leaf的类,我想制作Leaf的json响应实例的所有节点。 json响应如下:

JSON响应

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

我使用observable获得响应,并学会了第一个节点:

http.service.ts片段

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()));//maybe I could do something here?
}

这是我的Leaf课,以防万一:

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

我的最终目标是获取json树并以文件夹树格式表示它们。有没有办法使用map()遍历所有节点或map()和某种遍历的组合?

1 个答案:

答案 0 :(得分:2)

我首先为json数据创建一个接口:

interface LeafJson {
    name: string;
    state: string;
    children?: LeafJson[];
}

然后使用Array.map创建子项:

export class Leaf {
    name: string;
    state: string;
    treeData: Array<Leaf>;

    constructor(input: LeafJson){
        this.name = input.name;
        this.state = input.state;
        this.treeData = input.children ? input.children.map(item => new Leaf(item)) : [];
    }

    toggleState() {
        if (this.state=='active'){
            this.state = 'inactive';
        } else {
            this.state = 'active'
        }
    }
}

code in playground