gpt4 book ai didi

javascript - 尝试用字符串访问点表示法变量

转载 作者:行者123 更新时间:2023-11-28 03:10:05 25 4
gpt4 key购买 nike

我正在创建一个 Web 表单,它可以动态读取 swagger 端点来创建表单字段。具体来说,现在我正在尝试从 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,但试图避免这种情况。这是一个 React 应用程序,所以如果有人能想到一个可以提供帮助的库,我也会洗耳恭听。

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

关于javascript - 尝试用字符串访问点表示法变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60211333/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com