与带有对象的typescript(javascipt)映射

时间:2020-08-17 08:07:32

标签: javascript arrays json angular typescript

您好,我想根据这些内容来创建地图。..是否可以创建地图并编写更好的代码?

findViewDetailPolicy(policy) {
        if (policy['displayInfo']['displayTypeDetail']['displayType'] === 'STANDARD') {
          this.path = this.policyPathDetailStandard;
          this.router.navigate([this.path]);
        }
        if (policy['displayInfo']['displayTypeDetail']['displayType'] === 'PACCHETTO') {
          this.path = this.policyPathDetailModulare;
          this.router.navigate([this.path]);
        }
        if (policy['displayInfo']['displayTypeDetail']['displayType'] === 'SAVING') {
          this.path = this.policyPathDetailSaving;
          this.router.navigate([this.path]);
        }
        if (policy['displayInfo']['displayTypeDetail']['displayType'] === 'CQ') {
          this.path = this.policyPathDetailCq;
          this.router.navigate([this.path]);
        }
        if (policy['displayInfo']['displayTypeDetail']['displayType'] === 'COLLETTIVA') {
          this.path = this.policyPathDetailCollective;
          this.router.navigate([this.path]);
        }
      }

2 个答案:

答案 0 :(得分:3)

您的代码可以归结为:

findViewDetailPolicy(policy) {
    const map = { STANDARD: this.policyPathDetailStandard, ... };
    this.path = map[policy['displayInfo']['displayTypeDetail']['displayType']];
    this.router.navigate([this.path]);
}

答案 1 :(得分:1)

地图可能是这样的:

const mapToPathProp = {
    STANDARD: "policyPathDetailStandard",
    PACCHETTO: "policyPathDetailModulare",
    SAVING: "policyPathDetailSaving",
    CQ: "policyPathDetailCq",
    COLLETTIVA: "policyPathDetailCollective"
};

然后:

findViewDetailPolicy(policy) {
    let pathProp = mapToPathProp[policy.displayInfo.displayTypeDetail.displayType];
    if (pathProp) {
        this.path = this[pathProp];
        this.router.navigate([this.path]);
    }
}