如何在json中获得对动态生成(名称未知)子元素的引用



我有一个json,格式为:

"json": {
"schema": {
"type": "object",
"title": "My Table",
"properties": {
"table-1659555454697": {
"type": "array",
"items": {
"type": "object",
"properties": {
"inputTest": {
"type": "string"
},
"columnTwo": {
"type": "string"
}
},
"required": [
"inputTest",
"columnTwo"
]
}
}
},
},

我可以获得对";表-1659555454697";对象带有:

console.log(this.jsf.schema.properties);

我正在努力解决的是如何从该元素的孩子那里获得对";"必需";数组的长度。假设我不能引用";表-1659555454697";按名称,因为它是动态生成的。

我试过:

console.log(this.jsf.schema.properties[0].items[0].required.length);

但我得到了未定义的错误

您可能想要Object.keys、Object.values或Object.entries。它们分别提供对象的键、对象的值和对象的键值对的数组(作为[key, value]数组的数组(。

const propertyNames = Object.keys(json.schema.properties) // ["table-1659555454697"]
const propertyValues = Object.values(json.schema.properties) // [{ type: "array", items: { ... }]
const propertyEntries = Object.entries(json.schema.properties)
// [ ["table-1659555454697", [{ type: "array", items: { ... }] ]

所以我们可以这样做:

const requiredLength = Object.values(json.schema.properties)[0].items.required.length

您可以通过执行来引用表-1659555454697

Object.keys(this.jsf.schema.properties)[0]

最新更新