javascript - 尝试使用字符串访问点符号变量
问题描述
我正在创建一个可以动态读取 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++;
}
解决方案
你可以迭代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);
}
推荐阅读
- algorithm - 如果你得到 7 则返回 3 的所有方法,反之亦然 - 面试问题
- python - 从 Scrapy 中的 API 获取数据
- android - Webview 不在nestedscrollview 内的顶部开始
- php - 会话变量仅在 AJAX 脚本上消失
- java - 429 使用 aws-sdk 为 s3 对象生成预签名 URL 时请求过多
- java - 如何使用 CA 签名的服务器证书连接 SSL MQTT 客户端?
- c - C中结构的Typedef成员
- android - Android firebase 实施失败
- .net - Nuget 缓存与全局包文件夹
- excel - 从 Excel 打开 Word 文档并将其保存到新文件位置