首页 > 解决方案 > 尝试使用字符串访问点符号变量

问题描述

我正在创建一个可以动态读取 swagger 端点以创建表单字段的 Web 表单。具体来说,现在我正在尝试从 openAPI 3 定义的组件部分读取模式。

示例 json:

{
  "openapi": "3.0.1",
  "info": {
    .......
  },
  "paths": {
    ........
  },
  "components": {
    "schemas": {
      "FakeAppConfiguration": {
        "type": "object",
        "properties": {
          "setting1": {
            "type": "string",
            "nullable": true
          },
          "setting2": {
            "type": "string",
            "nullable": true
          }
        },
        "additionalProperties": false
      },
      "OtherFakeAppConfiguration": {
        ........
      },
      "ThirdFakeAppConfiguration": {
        ........
      }
      }
    }
  }
}

以这个 json 片段为例,我可以很容易地获取使用定义的模式的名称(json 已经使用 fetch 加载到数据中)

for (let schema in data.components.schemas)
{
    //this will print out FakeAppConfiguration, OtherFakeAppConfiguration, ThirdFakeAppConfiguration
    console.log(schema);
}

我现在的问题是尝试访问这些模式树中的每一个而不直接调用它们。我可以轻松地做 data.components.schemas.FakeAppConfiguration,但这会破坏使这个动态的目的。我一直在尝试以某种方式使用在上述循环中获得的字符串来访问我想要的无济于事。我尝试过的一些例子如下。任何人都可以帮助我获得进一步的访问权限,而无需使用点符号直接调用变量吗?我也考虑过手动解析 JSON,但试图避免这种情况。这是一个反应应用程序,所以如果有人能想到一个可以提供帮助的库,我也会全力以赴。

//treating like a key
data.components.schemas['FakeAppConfiguration']




//trying to create a map
interface SchemaDef {
    type: string,
    properties: Properties,
    //....etc,etc
}

let i = 0;
let schemas: Map<string, SchemaDef> = new Map<string, SchemaDef>();

for (let schema in data.components.schemas)
{
    schemas.set(schema, data.components.schemas[i]);
    i++;
}

标签: javascriptjsonreactjstypescript

解决方案


你可以迭代Object.entries()你的“模式”对象。

let schemas = {
      "FakeAppConfiguration": {
        "type": "object",
        "properties": {
          "setting1": {
            "type": "string",
            "nullable": true
          },
          "setting2": {
            "type": "string",
            "nullable": true
          }
        },
      },
     "FakeAppConfiguration2": {
        "type": "object",
        "properties": {
          "setting1": {
            "type": "string",
            "nullable": true
          },
          "setting2": {
            "type": "string",
            "nullable": true
          }
        },
      }

    };
      
for (let [key, value] of Object.entries(schemas)) {
    console.log(key, "\n\n", value);
}


推荐阅读