简体   繁体   English

自动将JSON对象映射到TypeScript对象(Angular 2)

[英]Map JSON object to TypeScript object automatically (Angular 2)

i'm new to Typescript and javascript. 我是Typescript和javascript的新手。 My question is: how from this 我的问题是:怎么做到这一点

``` ```

{
    "release": {
        "ref": {},
        "commits": {}
    },
    "debug": {
        "ref": {},
        "commits": {}
    },
    "feature": {
        "ref": {},
        "commits": {}
    },
    "hotfix": {
        "ref": {},
        "commits": {}
    }
}

``` ```

map it with with Typescript using interfaces 使用接口使用Typescript映射它

export interface IRepo { branches: IBranch; // how to make branches a of type string: IBranch dictionary? }

there will be unknown number of properties like debug, release, etc, i want to keep them as dictionary in IRepo instance 将有未知数量的属性,如调试,发布等,我想将它们保留为IRepo实例中的字典

i'm using this to fetch data: 我正在使用它来获取数据:

``` ```

getRepo() : Observable<IRepo> {
    if (!this.repo) {
        return this.http.get(this._baseUrl + 'repo.json')
            .map((res: Response) => {
                this.repo = res.json();
                return this.repo;
                })
                .catch(this.handleError);
    } else {
        return this.createObservable(this.repo);
    }
}

``` ```

You have a map that goes from some known string to an object of known structure (has ref commits ). 你有一个从一些已知 string到已知结构的对象的映射(具有ref commits )。 Just use a string indexer: 只需使用字符串索引器:

interface BranchByName {
  [branchName: string]: {
    ref: any;
    commits: any;
  } 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM