Javascript对象到对象的映射

时间:2016-04-02 16:38:26

标签: javascript typescript

考虑以下打字稿类:

export class Team {
    _id: any;
    name: string;
    tasklists: Array<Tasklist>;
}

export class Tasklist {
    _id: any;
    name: string;
    groups: Array<Group>;
}

export class Group {
    _id: any;
    name: string;
}

我想将Team类型的对象映射到此:

var nodeData =
[
    {
        category: team,
        text: "My team",
        nodes: [
        {
            category: "tasklist",
            text: "My tasklist",
            nodes: [
            {
                category: "group",
                text: "My group"
            }]
        }]
    }
];

我可以写一个函数来自己进行转换。但由于我是Javascript / Typescript的新手,我想知道是否有内置函数或可能是一个库,可以很容易地做到这一点。

1 个答案:

答案 0 :(得分:0)

您可以在班级中覆盖toJSON方法。这是一个工作示例:

class Team {
    constructor(private _id: any, private name: string, private tasklists: Array<Tasklist>) {}
    toJSON() {
        return {
            category: "team",
            text: this.name,
            nodes: this.tasklists
        }
    }
}

class Tasklist {
    constructor(private _id: any, private name: string, private groups: Array<Group>) {}
    toJSON() {
        return {
            category: "tasklist",
            text: this.name,
            nodes: this.groups
        }
    }
}

class Group {
    constructor(private _id: any, private name: string) {}
    toJSON() {
        return {
            category: "group",
            text: this.name
        }
    }
}

let team = new Team(
    1,
    "team_1",
    [
        new Tasklist( 
            12,
            "task_1",
            [
                new Group(
                    85,
                    "group_1"
                )
            ] 
        )
    ]
)

console.log(JSON.stringify(team, null, 4));

也是带有它的TypeScript游乐场的link

我使用Team []序列化更新了example