【问题标题】:map with typescript(javascipt) with object使用 typescript(javascript) 与对象映射
【发布时间】:2020-12-06 08:36:11
【问题描述】:

您好,如果.. 有没有办法创建地图并编写更好的代码,我想根据这些创建地图?

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]);
        }
      }

【问题讨论】:

  • switch case 可以完成这项工作。检查文档。 w3schools.com/js/js_switch.asp
  • 不是映射,但更好的方法是尝试将policy['displayInfo']['displayTypeDetail']['displayType'] 放入变量中并以更好的方式编写这些条件

标签: javascript arrays json angular typescript


【解决方案1】:

您的代码可以归结为:

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

【讨论】:

    【解决方案2】:

    地图可能是这样的:

    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]);
        }
    }
    

    【讨论】:

    • const mapToPathProp = { 标准:“policyPathDetailStandard”,PACCHETTO:“policyPathDetailModulare”,SAVING:“policyPathDetailSaving”,CQ:“policyPathDetailCq”,COLLETTIVA:“policyPathDetailCollective”};
    • 在这个对象中.. 使用哪种方法传递对象中的路径属性
    • 我不明白你在问什么。例如,pathProp 将是“polidyPathDetailStandard”,然后this[pathProp] 将就好像你做了this.polidyPathDetailStandard。这是否澄清了它?这种方法的优点是您只创建一次映射,而不是每次调用函数时。此外,当与任何if 条件不匹配时,接受的答案与您的代码的行为不同。
    猜你喜欢
    • 2021-10-10
    • 1970-01-01
    • 2014-11-07
    • 1970-01-01
    • 2018-04-04
    • 1970-01-01
    相关资源
    最近更新 更多